I am given the task to find the value of PI up to decimal poins 'x'
awhere 'x' is input through keyboard.
If I use c++ and use setprecision() defined in iomanip.h, I am getting
rounded off results. I need accurate truncated value. If I use c, I
can not use a variable in precision field in printf() . What can I do?

e.g. PI=3.1415(9265)
I am getting 3.1416

Please help
 

Vyom

The Power of x480
Staff member
Admin
Your approach is wrong.
You are just dividing 22 by 7 and expecting the results.

You need to develop some kind of loop to calculate the values 'manually'. Make a loop to keep dividing 22 by 7 and store the remainder in a variable.
After that its just a matter of executing loop until remainder isn't X.
 

nims11

BIOS Terminator
if x can be large, you need to develop a manual algorithm. But in that case, the problem is not simply performing a manual division of 22 and 7, as pi is irrational. 22/7 is an approximation which i think is valid upto about 10 decimal places. If x is small enough, a better approach will be acos(-1). Anyways, back to your question, eg you want to print pi truncating after 2 decimal places, one thing that can be done is
Code:
int(pi*100)/100.0
 
All build in data types (signed or unsigned) have data limit. You need to create a new class/data type that has no limit on the number of digits that can be stored in it. Think over how to do that, it's really easy.
 

Santa Maria!

Journeyman
Proof that 22/7 exceeds pi

But I'm guessing you're not that concerned about insane amounts of precision.
If it's just for display purposes, why don't you just use a string representation obtained from your calculation? Calculate the various digits and keep appending them to a std::vector<int(or char)>.
If you intend to use your truncated value for calculations... well, you better read up on the subtleties of floating point arithmetic.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
(I keep throwing this link around, but I still haven't gotten around to reading it fully myself :p)
 

pranav0091

I am not an Owl
Slightly off-topic, but Pi should be calculated as the sum of its infinite series and not as anything else if you want any arbitrary level of precision.

I am not much of a programmer, so this might be quite stupid, but why not use the infinite series and then calculate one digit at a time and store it as a text file or something. Have a look here: Chudnovsky algorithm - Wikipedia, the free encyclopedia
 
Last edited:

Anorion

Sith Lord
Staff member
Admin
130 mb text dump up to 100 mill digits here Pi to 100 million decimal places : QuickPi : Free Download & Streaming : Internet Archive
think that's the easiest way out
 
Top Bottom