What happen with this logic?

Hi Community

I'm see this question in a random Facebook group, I'm try to make a solution but don't understand what happen because test1 and test3 are de same (TRUE) :thinking:

test1 <- 58
test1 == 58

test2 <- test1/100

test3 <- test2*100



test3 < test1

# > test1 <- 58
# > test1 == 58
# [1] TRUE
# > test2 <- test1/100
# > test2
# [1] 0.58
# > test3 <- test2*100
# > test3
# [1] 58
# > test3==58
# [1] FALSE
# > test1==test3
# [1] FALSE
# > test3 < test1
# [1] TRUE

That is actually not equal, because R stored numbers (fractional or integers) in binary. But many fractionals (including 0.58) have no closed binary form, so they are approximated with a nearest binary representation, with numbers of precision equal to the storage dedicated to a fractional in r (64bit).
58 on the other hand gets stored as a usual binary, since it has a binary representation. But if you multiply the closest approximation of 0.58 in binary with 100, this will not be exactly 58, but a bit off. Hence, you see 58 (which is the correct result in decimal base), but in binary it's a little bit different and hence the conversion to decimal is a bit different as well (even if it is just in the 50th decimal place or somewhat).

You might want to read about transformation of numbers between binary and decimal and number srorage in R for further informations. :slight_smile:

1 Like

Hi @M_AcostaCH,
Floating-point arithmetic:

test1 <- 58
test2 <- test1/100
test3 <- test2*100

format(test1, digits=20)
#> [1] "58"
format(test2, digits=20)
#> [1] "0.57999999999999996003"
format(test3, digits=20)
#> [1] "57.999999999999992895"

Created on 2022-11-07 with reprex v2.0.2

1 Like

A solution would be to store both numbers as integers, so as.integer(0.58 * 100) and 58L for the other. This should be exactly equal.

1 Like

This can be a good tool to use

1 Like

Tnks! for all responses. All help me to understand the problems. Im going check more information about numbers between binary and decimal and number storage. :muscle:t4:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.