herugar5 herugar5 - 1 month ago 7x
C Question

Weird C program behaviour

I have the following C program:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>

int main() {
const int opt_count = 2;

int oc = 30;

int c = 900;

printf("%d %f\n", c, pow(oc, opt_count));
assert(c == (int)(pow(oc, opt_count)));

I'm running MinGW on Windows 8.1. Gcc version 4.9.3. I compile my program with:

gcc program.c -o program.exe

When I run it I get this output:

$ program
900 900.000000
Assertion failed: c == (int)(pow(oc, opt_count)), file program.c, line 16

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

What is going on? I expect the assertion to pass because 900 == 30^2.



I'm not using any fractions or decimals. I'm only using integers.


This happens when the implementation of pow is via

pow(x,y) = exp(log(x)*y)

Other library implementations first reduce the exponent by integer powers, thus avoiding this small floating point error.