Modulus operator does not work on float
-
when using the modulus (
%
) operator on floating point values, the result seems to always be converted to anint
, even if both sides of the operator arefloat
.code:
print(12.5 % 10)
has output:
2
expected output:
2.5
-
Floating point modulus isn't supported by all languages. I will put this one down as an enhancement rather than a bug.
-
I was assuming the compiler would give errors if things where not supported, but I noticed with multiple mistakes, that this is not the case for FUSE4, so in that sense I agree (since the goal is to get kids learning to code, not to create a professional/reliable coding environment).
-
@PB____ Well we certainly wan't it to be reliable. I will raise an issue for this
-
EDITED
this post:- because of a bug with negative values.
- because division by zero does not throw error (which is fair enough, but I need to throw a conditional error in my code, so I solved it differently)
I wrote the following function to execute modules on float in FUZE4, and so far this seems to work for me:
// attempt 3: function modulus(num, div) if div == 0 then throw_division_by_zero() // undefined function endif sign = 1 if num < 0 then sign = -1 endif num = abs(num) div = abs(div) while num >= div loop num -= div repeat return div * sign
Since my previous attempt did not behave well with negative numbers, I've now tested this pattern with the following JavaScript (no that JavaScript should be taken as the ultimate example, but it accepts float for modulus and can easily run an experiment from within the browser):
(function module() { console.log('start'); function modulus(num, div) { !div && throw new Error(‘division by zero’) var sign = num < 0 ? -1 : 1; num = Math.abs(num); div = Math.abs(div); while(num >= div){ num -= div; } return num*sign; } for(var i = -4; i<4; i+=.75) { for(var n = -4; n<4; n+=.75) { if(n === 0) continue; // prevent division by zero a = i % n; b = modulus(i,n); if(a!=b){ console.log(a, b, i, n) } } } console.log(' end' ) }())