开发者

Creating custom data type in c++

I'm writing a program to find the value of pi, and want it to show more than the standard 16 decimal places. How do I create a variable that can hold more than 16 decimal places? My current program is written below. Using Dev-C++:

#include<iostream.h>
#include<conio.h>
#include<math.h>

int factorial(int a)
{
    int b=1,c=1;
    for(c; c<=a; c++)
    {
        b=b*c;
    }
    return b;
}

int main()
{
    cout.precision(300);
    long int n,a;
    long double z=0,pi,num,den;
    for(n=0; n<1000000; n++)
    {      //begin for
        num=(pow(factorial(2*n),3))*((42*n)+5);
        den=(pow(factorial(n),6))*(pow(16,(3*n)+1));
        z=z+(num/den);

        pi=1/z;
        if(n%1==0)
        { 
            cout<<z<<endl; //test print statement
            ci开发者_StackOverflown>>a;
            cout<<pi;
            cout<<endl;
        }
    } 
    getch();
    return 0;      //end for
}


If you don't want to use an existing high-precision arithmetic library, then here are a few pointers for writing your own. It will be a fair amount of work (and quite fiddly to debug), but quite a good learning exercise if you've got the time.

  • Store each number as an array of smaller "digits". For a very simple (but inefficient) implementation, these could literally be decimal digits, with values from 0 to 9 - this will then be very easy to print. For a more efficient implementation, I'd probably use 32-bit values for the "digits". You'll also need to decide how to represent negative numbers, whether the array should be fixed or variable size, and (for working with non-integers) whether the decimal point should be fixed or floating.

  • Implement basic arithmetic using the algorithms you learnt in primary school: addition with carry, subtraction with borrow, long multiplication and long division.

  • pow and factorial, needed for your algorithm can be implemented simply as repeated multiplication; other algorithms are available if this isn't fast enough (and for functions like sqrt and sin that can't be represented exactly with basic operations).


Sounds like you want a bignum library. Have a look at the GNU Multiple Precision Arithmetic Library for a widely-used open source alternative.


You can use one of the bigint libraries on the internet, for example: https://mattmccutchen.net/bigint/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜