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))