Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding Pi in Perl to the 100 millionth decimal place?

Tags:

rounding

pi

perl

For a Science Fair project, I am testing how your choice of programming language could affect performance. I am doing this by making scripts in Java, Ruby, Perl, and Python to calculate Pi to the 100 millionth decimal place. I'm starting with Perl, since I'm most familiar with Perl. However, this brings an interesting problem to the table. I need to round Pi to the 100 millionth digit in Perl, but as far as I can see, Perl has no good rounding method for this situation. There's only stuff like

use Math::Round;
$rounded = nearest(0.1, $numb);

And that's a bit of a problem, since I don't want to sit at my computer typing 100 million zeros. As far as I know, sprintf and printf aren't any better; plus, they have that annoying half to even thing. Can anyone help out?

P.S. I'm planning to use the Chudnovsky Formula, if it matters to anyone.

like image 476
slinky773 Avatar asked Dec 26 '22 12:12

slinky773


2 Answers

I don't think any programming language can natively do what you are asking. Even bignum libraries like Math::BigRat (default 40 digits) and Math::Bignum cannot do 100 million digits.

To make it happen, you will have to create your own custom way to represent such big numbers and how to round them.

like image 84
mvp Avatar answered Jan 12 '23 15:01

mvp


Think about the problem in another way. You need to round to 100 million (1E8) digits but you don't need to process all 1E8 digits in one go to do that.

Instead,

  1. Use the Chudnovsky Formula to calculate 1E8 +1 digits.
  2. Store the digits in a string (if you have the memory) or a file.
  3. Select the last n (something small like 8 or even 2) digits.
  4. If they aren't all 9 round to n-1 digits.
  5. If they are then convert them to (n-1) * 0 digits. Then read the next n digits from the end and repeat 4 and 5.

However, if the goal is to test relative performance of languages by generating 1E8 digits of Pi then why bother focus on the rather artificial constraint of rounding that number. If you use the same algorithm then any language should produce the same result. And you have a 50% chance of generating a rounded number anyway.

like image 42
jmcnamara Avatar answered Jan 12 '23 15:01

jmcnamara