1

So, I ran this code on my code blocks:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int a;
    a=pow(10,9);
    cout<<a<<endl;
    a=ceil(pow(10,9));
    cout<<a<<endl;
    a=floor(pow(10,9));
    cout<<a<<endl;
    return 0;
}

I got the output as:

 999999999
 100000000
 100000000

1st output was not 10^9 due to truncation effect,which means that pow(10,9) was something like 999999999.99999.., but then how come floor of this thing is 1000000000 ??

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
kik20
  • 19
  • 2
  • 2
    On my machine it prints `1000000000` three times. See also http://ideone.com/qLIp33 – moooeeeep Dec 15 '14 at 08:05
  • 2
    Welcome to floating point, where _nothing_ is as it seems :-) – paxdiablo Dec 15 '14 at 08:05
  • What machine and compiler and OS are you using? Can you also try printing the three values as hex bytes? – John Zwinck Dec 15 '14 at 08:11
  • 1
    `pow(10,9)` might be treated differently in the two invocations... for example, on x86 it might be rounded up when converting from an 80-bit register to an intermediate 64-bit `double` value that's the input to `floor`, whereas the to-`int` conversion just truncates. – Tony Delroy Dec 15 '14 at 08:17
  • The only way to answer your question would be by inspecting the assembler output from the compiler. It may well be that the `trunc(pow(10,9))` is turned into a integer calculation that is precise (multiplying 10 * 10, then that by itself to give 10^4, and again to give 10^8, and then multiply by 10 again - or simply constant folded from something like that), where the compiler isn't making the same optimisation in the first case (for reasons that I don't quite understand, but compilers work in mysterious ways at times) – Mats Petersson Dec 15 '14 at 08:18
  • my compiler: mingw32-g++, OS is windows 8 – kik20 Dec 15 '14 at 08:26
  • this is probably a bug in the library. see from the definition http://linux.die.net/man/3/pow. when you do a = pow(10,9), it uses the integer (long) version, which should not have truncation, floor, or rounding issues. – thang Dec 15 '14 at 08:32
  • possible duplicate of [Why pow(10,5) = 9,999 in C++](http://stackoverflow.com/questions/9704195/why-pow10-5-9-999-in-c) – phuclv Sep 06 '15 at 05:14

1 Answers1

-1

Actually, the maximum value for int is 2,147,483,647, therefore there should be no overflow or truncation (it's an int). And my output is exactly:

1000000000 1000000000 1000000000

rookie coder
  • 141
  • 1
  • 8
  • http://stackoverflow.com/questions/9704195/why-pow10-5-9-999-in-c;similar question has already been brought up but here the main concern is with the floor() function misbehaving – kik20 Dec 15 '14 at 08:29
  • the floor function is not misbehaving. what is likely the issue is that the pow (long version) misbehaves. – thang Dec 15 '14 at 08:34