How does C++ work with large numbers? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How does C++ work with large numbers?

I have a code that tries to solve an integral of a function in a given interval numerically, using the method of Trapezoidal Rule (see the formula in https://dev.to/juanroalvarado/functional-approach-to-trapezoidal-rule-integration-m68 ), now, for the function sin(x) in the interval [-pi/2.0,pi/2.0], the integral is waited to be zero. In this case, I take the number of partitions 'n' equal to 4. The problem is that when I have pi with 20 decimal places it is zero, with 14 decimal places it is 8.72e^(-17), then with 11 decimal places, it is zero, with 8 decimal places it is 8.72e^(-17), with 3 decimal places it is zero. I mean, the integral is zero or a number near zero for different approximations of pi, but it doesn't have a clear trend. I would appreciate your help. Code: https://code.sololearn.com/ca9a21A7A17A

22nd Mar 2021, 4:52 PM
Krys
Krys - avatar
1 Answer
+ 5
c++ compiles to machine code so your question of how double type c++ numbers work breaks down to how CPU's work with floating point numbers. Most-likely Sololearn's Code Playground uses x86 CPU's to run their compiled c++ code. double from c++ with most modern c++ compilers is a IEEE-754 floating-point. That's a 64-bit number that can be understood as basically an exponential form of a number with a range for exponent and most bits used to make the coefficient as accurate as possible within the available bits. More detail on IEEE-754 is at: https://en.wikipedia.org/wiki/IEEE_754 For x86, sin of a radian angle breaks down to a machine code instruction that is represented in assembly by fsin. Different instructions are used for floating point addition(fadd, faddp...), multiplication(fmul, fimul, fmulp...)... Every operation can add error. You could use "long double" but that probably won't gain you a lot. More details are at: https://en.wikipedia.org/wiki/Long_double If you want arbitrary precision, try https://www.boost.org/doc/libs/1_59_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/tutorial/using_arbitrary_precision_floating_point_types.html
22nd Mar 2021, 5:47 PM
Josh Greig
Josh Greig - avatar