Home > OS >  Why is the result in the below code 1? when exactly does rounding happen?
Why is the result in the below code 1? when exactly does rounding happen?

Time:10-24

Could someone please explain why the result in the below code is 1?

> a <- 2^(-52)
> c <- 1
> a c

If, in the above code, "a" gets rounded to 0 or something while adding, then why does the below code does not return a zero?

> a <- 2^(-52)
> b <- 2^(-53)
> a b

CodePudding user response:

You need to read up on floating point arithmetic: this question doesn't cover your exact question, but gives useful references (more here). The difference between the two examples is that in the first case the addends are on very different scales, while in the second case they are of similar magnitudes. ?.Machine will give you some of the relevant values, especially .Machine$double.eps (which is the smallest number such that 1 x > x) (although it won't explain floating point arithmetic for you).

(@BrianMontgomery's answer points out that technically this is only true if you use a <- 2^(-53) (or smaller).)

(I don't think this answer is great, but it will do until someone wants to come along and explain the floating point issues underlying this example in more detail.)

CodePudding user response:

It's not really 1, R just doesn't display it by default.
Also, don't use c as variable in R, as c() is the combine function.

a <- 2^(-52)
d <- 1
e <- a   d
e # shows 1
e - 1 # gives [1] 2.220446e-16
  •  Tags:  
  • r
  • Related