non-integer_20modulo_20operation

This is an old revision of the document!


Non-integer modulo operation

by Richard Russell, November 2011

BBC BASIC, in common with several other languages (e.g. C), provides only an integer MOD operator as standard. That is, you can pass non-integer values to MOD but they will be truncated to integers before the operation is carried out. For example:

      PRINT 678.9 MOD 123.45

prints the value 63.

However the modulo operation is not fundamentally limited to integer values and occasionally it can be useful to have a version which will work with non-integers. In C this is provided by the fmod library function. An equivalent function in BBC BASIC can be implemented as follows:

      DEF FNfmod(x,y) = x - x DIV y * y

Now we can perform the following operation:

      PRINT FNfmod(678.9, 123.45)

and the value printed is 61.65.

The FNfmod function listed above is restricted to values in the range -2147483648 to +2147483647 because of the use of the DIV operator. If you need an extended range (assuming *FLOAT64 mode is in use) the following function may be used:

      DEF FNfmod(x,y) = x - SGNx * INT ABS(x/y) * ABSy
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
non-integer_20modulo_20operation.1522502369.txt.gz · Last modified: 2024/01/05 00:17 (external edit)