Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

precision - generating pi to nth digit java

I wanted to know how I can generate pi to the nth digit. I have a couple of basic ideas.

  1. Use Math.PI and increase the precision (if that's possible)
  2. Use Euler's formula to generate pi but even here, I would need to increase the precision (I think) Euler's formula for PI
  3. There is also Srinivasa Ramanujan's formula for generating PI which is known for it's rapid convergence. This formula seems difficult to implement. I believe, I would have to also increase deicmal precision here.
    enter image description here

So in short, either way, I would need to increase the precision of BigDecimal depending on what the nth digit is. How would I go about increasing the precision of BigDecimal to nth digit? Also, if there is a better and faster of doing this, can you please point me in the correct direction.

EDIT: I just want to generate PI. I don't want to use for calculations. and this is a question about how I can use BigDecimal to implement my ideas of generating PI.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • Math.PI is of type double. That means about 15 decimal digits of precision, and that is all the data you have; nothing will magically make additional digits of PI appear.
  • BigDecimal has arbitrary precision. setScale() allows you to create BigDecimal objects with as much precision as you want and most of the arithmetic methods will automatically increase precision as required, but of course the more precision, the slower all calculations will be.
  • The most difficult part of implementing Ramanujan's formula will ironically be the sqrt(2) in the constant factor, because there is not built-in sqrt() for BigDecimal, so you'll have to write your own.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...