Using sqrt function in c++ -


so, using sqrt function in c++ , problem facing is, when input sqrt 40000000001, returns 200000.

#include <iostream> #include <cmath>  using namespace std;  int main (void) {     long long int a;     cin>>a;     double b = sqrt(a);     cout<<b<<"\n";     return 0; } 

why happening?

it should return 200000.0000025 , need exact value. getting 200000 produces wrong answer. thanks!

adding

cout << "a=" << << endl; 

will reveal when enter 40000000001 value of a 46341. because represent 40000000001 in int you'll need 36 bits, while on platform, int has 32 bits (31 plus 1 sign).

using long instead, 200000 result. the fact don't 200000.0000025 must have fact doubles have limited amount of precision. though wikipedia says 64 bit double has precision of typically 15-17 decimal digits , number looking has 13 significant digits, suspect there roundoff errors in intermediate steps of calculation.


part of problem printing, if print example:

    cout << b - 200000 << endl; 

then

    2.49999e-06 

as output close 0.0000025 . can increase number of digits printed:

    cout << setprecision(13) << b << endl; 

which prints 200000.0000025 on platform.


if need more precision primitive types provide, there libraries that, see e.g. this list on wikipedia. in particular, boost seems have library , here example taking square root of 100 digit number: square root of 100 digit number in c++


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -