2

I'm very confused. In R I type

print(pi,20)

and I get this output

3.141592653589793116

The last 3 digts 116 should be 238. How can that be?

Also, is it possible to get more digits of pi in R ?

Ole Petersen
  • 670
  • 9
  • 21
  • 1
    See this: https://en.wikipedia.org/wiki/Floating_point Computers store values with a finite number of bits and have limited precision. – nicola Nov 06 '15 at 12:59
  • There are packages that enable using arbitrarily precise numbers, but of course you'd need then to somehow get or calculate a value of pi with the desired precision. – Roland Nov 06 '15 at 13:03
  • 1
    you can use the `Rmpfr` package and `Const("pi", prec = 260)` to have corrects digits for pi – etienne Nov 06 '15 at 13:04
  • `pi` is a predefined constant, it's not calculated at runtime. You are seeing the limitations of `print`, not inaccuracies in the constant. Try `sprintf("%.100f",pi)` – Panagiotis Kanavos Nov 06 '15 at 13:06
  • @Roland, the reason to close is *wrong*. This isn't about *floating point numbers*, it's about the way R calculates `pi`. In fact, @etienne already provided a *correct answer*. A *different* package contains a better constant value – Panagiotis Kanavos Nov 06 '15 at 13:27
  • [Checking the source](https://github.com/RevolutionAnalytics/RRO/blob/master/R-src/src/library/base/R/constants.R) it looks like `pi` *is* calculated in a coarse way as `4*atan(1)`. This has nothing to do with floating point calculations. The actual culprit is how `atan` is calculated in R. Etienne's comment should be the correct answer – Panagiotis Kanavos Nov 06 '15 at 13:31
  • I'ts very strange that R uses 4*atan(1) instead of raw digits of the true pi. – Ole Petersen Nov 06 '15 at 13:40
  • @PanagiotisKanavos atan(1) is exactly pi/4. That it isn't in R is a consequence of floating point imprecision and the approximations necessary to calculate it on a computer. And of course, the Rmpfr package implements arbitrary precise numbers. – Roland Nov 06 '15 at 13:59
  • Anyway, I've reopened it. Feel free to submit an answer. – Roland Nov 06 '15 at 14:11
  • I just read the comments. Maybe I'm missing something, but is someone here implying that a computer could store pi _exactly_? – nicola Nov 06 '15 at 15:14

0 Answers0