The next code sqrt(x) and sqrt(x) * sqrt(x) ist distinc to x, becouse?
I'm using boost to handle large numbers but the square of the root is different from the original number and that worries me, do you know how I could get the original number x?
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main() {
boost::multiprecision::cpp_int num= 7459874565236544789;
boost::multiprecision::cpp_int num_sqrt= sqrt(num);
boost::multiprecision::cpp_int num_sqrt_square= num_sqrt*num_sqrt;
cout << "\n num: " << num <<
"\n num_sqrt: " << num_sqrt <<
"\n num_sqrt_square: " << num_sqrt_square <<
"\n _num_sqrt_square: " << sqrt(num) * sqrt(num);
}
I expect that sqrt(x) * sqrt(x) = x, but the output:
num: 7459874565236544789
num_sqrt: 2731277094
num_sqrt_square: 7459874564209084836
_num_sqrt_square: 7459874564209084836
num != num_sqrt_square !!!
The square root of a non-perfect square is an irrational number, so it is not possible to represent it finitely and
√x √x = xcan't be achieved exactly.As a workaround, you can perform the comparison with a relative tolerance.
In general, in such situations it is simpler to keep the original value and use the square root only where essential.