problems with pow()

Hello,
for example int his code, pow(a,2) doesn't give the same value of a*a
1
2
3
4
5
{int a;
a=pow(60,2);
int b=60*60;
cout <<a<<" "<<b;
}

the output here is
3599 3600
can someone explain me why?
Thank you in advance
I honestly have no idea. I put it into Visual Studio and correctly received 3600 3600. No warnings or anything. That's... strange.
Possibly the implementation may use something like
exp(2*log(60))
which will give an approximate result using floating-point values.
1
2
    std::cout.precision(20);
    std::cout << exp(2*log(60)) << '\n';

Output:
3599.999999999998181
the interesting thing is that when I make a program:
1
2
3
{
cout <<pow(60,2);
}

the output is:
3600

cannot understand this c++...
I think that pow doesn't work well with integers
also look this program that calculates volume of a sphere:
1
2
3
4
5
6
7
8
int main()
{
    int a;
    cin >>a;
    cout <<"VOLUME = ";
    printf ("%.3f",a*a*a*4*3.14159/3);
    cout<<endl;
}

for input 1523
the output is
VOLUME = 1304460194.187

and in this program:
1
2
3
4
5
6
7
8
int main()
{
    int a;
    cin >>a;
    cout <<"VOLUME = ";
    printf ("%.3f",pow(a,3)*4*3.14159/3);
    cout<<endl;
}

the output is
VOLUME = 14797486501.627

which appears to be right...
again, why is there difference?
Most of the unexpected results arise from truncation which occurs either when converting from floating-point to integer,
1
2
3
4
5
    int d = 3599.99999999999;
    cout << d << '\n';
	
    int e = round(3599.99999999999);
    cout << e << '\n';
3599
3600

or when exceeding the capacity of an integer.

1523*1523*1523*4 gives
14130570668
which requires more than 32 bits, and is truncated to
1245668780
The difference is 3*2^32

That leads to the incorrect result 1304460194.187

Recommendations. Use type double for floating-point work. Avoid mixing integer and floating-point types in the same calculation.

Constants such as 4 or 3 are integers, use 4.0 and 3.0 which are type double instead.


edit:
note also, cout << 3599.99999999999 << '\n'; result is
3600
Since the default precision for cout is 6 significant digits, the displayed result is rounded before being shown, the extra digits are still there, they are simply not displayed.
Last edited on
ok, thank You very much
Topic archived. No new replies allowed.