Reputation: 411
What I want to do is to calculate square root of a number N and than we have to store this square root with P correct decimal values.For example
Lets,N=2 and P=100
//I want to store square root till P correct decimal values
like storing
1.41421356237309504880...till 100 values
EDIT - Initially I asked question for specifically c++ but as told by vsoftco that it is almost impossible for c++ to do this without boost.So I have tagged python too and not removed c++ tag in hope for correct answer in C++
Upvotes: 1
Views: 291
Reputation: 16090
Well, there is a proposed extension to c++ that defines a decimal
type family described in http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2849.pdf. There is some support for it in modern gcc version, however it's still not full, even in 4.9.2
Maybe it will be feasible for you.
Upvotes: 0
Reputation: 56577
C++ uses floating-point types (such as float
, double
etc) to store floating-point values and perform floating point arithmetic. The size of these types (which directly influences their precision) is implementation-defined (usually you won't get more than 128 bit of precision). Also, precision is a relative term: when your numbers grow, you have less and less precision.
So, to answer your question: it is impossible to store a number with arbitrary precision using standard C++ types. You need to use a multi-precision library for that, e.g. Boost.Multiprecision.
Example code using Boost.Multiprecison:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
int main()
{
using namespace boost::multiprecision;
typedef number<cpp_dec_float<100> > cpp_dec_float_100; // 100 decimal places
cpp_dec_float_100 N = 2;
cpp_dec_float_100 result = sqrt(N); // calls boost::multiprecision::sqrt
std::cout << result.str() << std::endl; // displays the result as a string
}
If you use Python, you can make use of decimal
module:
from decimal import *
getcontext().prec = 100
result = Decimal.sqrt(Decimal(2))
print("Decimal.sqrt(2): {0}".format(result))
Upvotes: 1