Fraction function

BlitzMax Forums/BlitzMax Beginners Area/Fraction function

Kistjes(Posted 2007) [#1]
Hello,

I need to know the fraction of a float (or double). So I tried
Function fraction:Double(f:Double) 
	Return f - Int(f) 
End Function

and I tried:
Function fraction:Double(f:Double) 
	Return f - Floor(f) 
End Function


This is what happens:
print fraction(1.2)
output > 0.20000004768371582

or this:
print fraction(1.93)
output > 0.92999994754791260


This is wrong (of course) and not accurate enough. Anyone an idea?

[edit]
Whoaah? What's this?
Just for a test I tried
Print 1.2 - 1.0
Print 1.2
output:
0.200000048
1.20000005
It looks like it's a rounding thing for the print-function, isn't it?
So, in that case, there is nothing wrong with the function. Whew!


Czar Flavius(Posted 2007) [#2]
Nope, it's not print specific, and it's not a problem with your functions. Floating point values are only accurate to a certain number of decimal places. This is because it is not possible to store all decimal fractions exactly in binary format. (Trying to express 1/3 or 2/3 in decimal is similar - you can't do it exactly for infinite decimal places).

For most purposes I'd say 0.93 being represented as 0.9299999 is accurate enough for even important calculations, unless you are doing something which is needs to be extremely accurate. In that case you will need to find an alternate method. For example, store the fraction part as an integer along with an (inverse) exponent.

For example, 1.2 would be stored as 2 with an exponent 10, meaing you must divide 2 by 10 to get the desired .2 . This will represent the value accurately for display or storage, but when you use it into a calcuation it will just be used as the floating point value again.

But I think you'll find the inaccuracy is negligible. Try it ;)