C ++ computes more accurate than double or long double

I teach myself C ++ and this practice question , he asks to write code that can calculate PI up to β†’ 30 digits. I found out that double / long double are 16 digits that exactly match my computer.

I think the lesson of this question is to be able to calculate accuracy beyond what is available. So how do I do this? Is it possible?

my code to calculate Pi now

#include "stdafx.h" #include <iostream> #include <math.h> #include <iomanip> using namespace std; int main(){ double pi; pi = 4*atan(1.0); cout<<setprecision(30)<<pi; return 0; } 

The output is 16 digits, and for comparison - from pi to 30 digits.

 3.1415926535897931 3.141592653589793238462643383279 

Any suggestions for improving accuracy or is it something that doesn't ever matter? Alternatively, if there is another lesson, you think I should study here, do not hesitate to offer it. Thanks!

+6
source share
2 answers

You will need to perform the calculation using some other method than floating point. Libraries exist for performing β€œlong math,” such as GMP .

If this is not what you are looking for, you can also write code to do it yourself. The easiest way is to just use a string and save the number per character. Do the math as if you were doing it manually on paper. Adding numbers together is relatively easy, so subtracting. Doing multiplication and division is a little harder.

For non-integer numbers you need to make sure that you are building a decimal point for adding / subtracting ...

It’s a good learning experience to write this, but don’t expect it to be what you knock out in half an hour without thinking [add and subtract, maybe!]

+8
source

You can use quad math , the built-in type __float128 and q / q suffixes in GCC / clang.

 #include <stdio.h> #include <quadmath.h> int main () { __float128 x = strtoflt128("1234567891234567891234567891234566", nullptr); auto y = 1.0q; printf("%.Qf", x + y); // there is quadmath_snprintf, but this also works fine return 0; } 
0
source

All Articles