2

I wanted to calculate that term:

(21000*(1.022^7-1))/(1.022-1)

R tells me, it's 157065.7. This was my answer to a task that I had to solve. It was stated that this answer is not correct, the correct answer should be 157065.67. Then I calculated this with my calculator on my smartphone and indeed, the solution was 157065.67034. I am really wondering what is wrong with R and whether I can change some options. I've tried options()$digits but that's 7, this can't be the problem...

Ian Gow
  • 3,098
  • 1
  • 25
  • 31
TobiSonne
  • 1,044
  • 7
  • 22

3 Answers3

4

One option:

formatC((21000*(1.022^7-1))/(1.022-1), digits = 11)
#> [1] "157065.67035"

Created on 2021-06-24 by the reprex package (v2.0.0)

Ian Gow
  • 3,098
  • 1
  • 25
  • 31
3

Use options(digits = 15). Note that this changes globally the format. Also, the number of digits indicates all the digits (before and after the decimal separator).

Pedro Alencar
  • 1,049
  • 7
  • 20
  • Greath, thank you, I wanted to change that globally. I will accept the answer as soon as it's possible. Is every number rounded at each intermediate step? – TobiSonne Jun 24 '21 at 15:30
  • Usually R rounds number to the nearest (up or down) and to the even side if it ends in 5 (0.35 -> 0.4) – Pedro Alencar Jun 24 '21 at 15:32
  • the `digits` option does not change the *internal* precision of any of the calculations (which are done with standard 64-bit floating point math), only the number of digits printed in the output – Ben Bolker Jun 24 '21 at 16:21
2

Here's how you would display more decimals.

print((21000*(1.022^7-1))/(1.022-1), digits=16)
[1] 157065.670346861

There's nothing "wrong" with R in this respect. Decisions have to be made about how to print floating point values to the console.

Bill O'Brien
  • 862
  • 5
  • 14