schemegambit

Gambit scheme incorrect calculation for numbers with decimals


i'm using gambit-c intepreter to evaluate scheme arithmetic operations, but it's results are bit off. for example i execute (+ 23 20.01) and it gives me 43.010000000000005, instead of 43.01.

This only occurs if i use numbers with 2 decimal points.

Is there a fix for this?


Solution

  • It has to do with how floating point calculations are done. Please read What Every Programmer Should Know About Floating-Point Arithmetic.

    You are in luck! In Scheme you fix this by using exact numbers:

    (+ 23 #e20.01) ; ==> 4301/100
    

    You can make it inexact with:

    (exact->inexact (+ 23 #e20.01)) ; ==> 43.01