fmod() in BASIC

Discussions related to mathematics, numerical methods, graph plotting etc.
Post Reply
p_m21987
Posts: 128
Joined: Mon 02 Apr 2018, 21:51

fmod() in BASIC

Post by p_m21987 » Fri 23 Nov 2018, 17:27

Hello,

I found myself in the situation where I needed to use the fmod() function in a BASIC program. As far as I know, BBC BASIC doesn't have fmod, so I (as far as I knew) needed to implement it myself. This is what I came up with:

Code: Select all

DEF FNfmod( a, b )
b=ABSb*SGNa
=a-b*INT(a/b)
Does it seem sensible/efficient? Are there any bugs or potential problems, or is there a more sensible way of doing it? My intention was for it to behave the same way fmod() behaves in C.

DBZ FOREVER!!! !!! !!! !!!

guest
Posts: 268
Joined: Mon 02 Apr 2018, 09:12

Re: fmod() in BASIC

Post by guest » Fri 23 Nov 2018, 18:42

Patrick M wrote:
Fri 23 Nov 2018, 17:27
Does it seem sensible/efficient? Are there any bugs or potential problems, or is there a more sensible way of doing it?
I can't see anything obviously problematical. If speed is critical this was a little faster in my tests (the difference was more significant with the 64-bit interpreter):

Code: Select all

DEF FNfmod(x,y)
LOCAL n%
n%=x/y
=x-y*n%
If you can justify omitting the LOCAL statement (so that n% becomes a global) the benefit is even greater.

p_m21987
Posts: 128
Joined: Mon 02 Apr 2018, 21:51

Re: fmod() in BASIC

Post by p_m21987 » Fri 23 Nov 2018, 18:49

Nice! As it will be used as part of a game program, any speed improvement will be welcome. I'll use your method, and probably omit the LOCAL statement.

Thanks very much.

guest
Posts: 268
Joined: Mon 02 Apr 2018, 09:12

Re: fmod() in BASIC

Post by guest » Fri 23 Nov 2018, 20:03

Patrick M wrote:
Fri 23 Nov 2018, 18:49
any speed improvement will be welcome.
Function calls are quite expensive, so if you're wanting to shave off every nanosecond put the code inline.

jgharston
Posts: 4
Joined: Thu 05 Apr 2018, 14:08

Re: fmod() in BASIC

Post by jgharston » Mon 22 Apr 2019, 04:00

guest wrote:
Fri 23 Nov 2018, 18:42

Code: Select all

DEF FNfmod(x,y)
LOCAL n%
n%=x/y
=x-y*n%
If you can justify omitting the LOCAL statement (so that n% becomes a global) the benefit is even greater.
The x/y is only used once, and without side effects, so - if x and y are always positive - you could do:

Code: Select all

DEFFNfmod(x,y)=x-y*INT(x/y)
And, as previously mentioned, for the greatest speed, inline it. Instead of z=FNfmod(a,b) do z=a-b*INT(a/b), with the disdvantage of losing the coding symantics that tells you what it's doing.

If x or y could be negative you need to use the n%= method to truncate the integer towards zero, INT truncates the integer towards negative infinity.

Post Reply