0

I know that running a simple line such as sqrt(2) ^ 2 == 2 will return FALSE, but when I create an object with the left part of the equation, it returns the value 2, but when logically comparing the object to the number 2, I still get FALSE. This seems to be in error. Here is the code:

> (root.of.2 <- sqrt(2))
[1] 1.414214
> (root.of.2.sqrd <- sqrt(2) ^ 2)
[1] 2
> (root.of.2.sqrd == 2)
[1] FALSE

What’s going on here?

Canned Man
  • 734
  • 1
  • 7
  • 26

2 Answers2

3

Look closer at your variable:

> print(root.of.2.sqrd,18)
[1] 2.0000000000000004

root.of.2.sqrd is numeric.

> as.integer(root.of.2.sqrd)==2
[1] TRUE

Read FAQ 7.31

By the way, there are similar questions.

Community
  • 1
  • 1
Katin
  • 177
  • 1
  • 13
1

They are different numbers (sqrt(2) being irrational at some point of time some numerical inaccuracy, however small, will be introduced with it's rational approximation):

print(sprintf('%.20f', 2))
#[1] "2.00000000000000000000"
print(sprintf('%.20f', sqrt(2) ^ 2))
#[1] "2.00000000000000044409"
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63