mardi 7 juillet 2015

R created too much (unwanted) digits

I'm new in R but I currently have a problem with the declaration and the process of calculation into R. When I declare a variable or I calculate a new one, R creates some unwanted digit which can be seen only if I choose to display a lot of digits.

An example just under :

    r <- 1.986
    r
    [1] 1.986
    print(r,digits=20)
    [1] 1.9859999999999999876

The problem is that when operations are made, the unwanted digits are taken into account and the output is not exactly what I wanted : (105*1.986=208.53)

    k <- 105*r
    print(k,digits=20)
    [1] 208.53000000000000114

It creates a error in each output of my function (like an error of 40 when I expected 1850 as a result, which is not trivial). I can't round each variable I have because there is a lot of equation, calculation and all that in a big loop, so it will create too much delays. (I want to have a efficient code if possible)

Where does this "mistake" come from ? How can I correct that ?

Thanks for any help !




Aucun commentaire:

Enregistrer un commentaire