0

I am facing a strange issue with the below code,

 uint32 number = 1000000000;
 number = number * pow(10, -9);
 printf("number is %d\n", number);

I see the number getting printed as "0", while I expect the number to be "1". Can anyone point what is possibly causing this? This is on MPC8248 platform.

Thanks in advance.

mk

Keeler
  • 2,102
  • 14
  • 20
iammk
  • 1
  • 1

2 Answers2

3

pow returns a double, and with doubles you must always worry about precision. The product number * pow(...) may not return exactly 1. It could be 0.99 or something else that's almost 1 but not quite. When this value gets assigned back to the unsigned integer number, it would get demoted to become an int, and rounded down to 0.

To get around this, you can always implement your own pow function with integers. I'd recommend implementing with longs, though, because your integers can overflow fast (e.g. base = 50, exponent = 6 easily exceeds 32-bits typically allotted to ints).

See answers to this SO question for more details on the pow issue.

Wait, what's precision?

Many numbers cannot be expressed with a finite binary representation. The float type is one such finite binary representation. A float can only store a certain number of bits of information (which you can think of as precision), so any bits that don't fit are discarded. This loss of information is why floating point numbers can have errors like these. You can read more about this here.

Community
  • 1
  • 1
Keeler
  • 2,102
  • 14
  • 20
0

number = number * SomeFloat

integer multiplied by floating numbers ? Should give a floating point number. Result assigned in a integer variable ? Float gets implicitely converted to an integer ??? Danger !

Use the round function, at least, as suggested by comments.

Don't expect number artihmetics in your computer being the same that numbers in math as you were taught in school (at least, not exactly)

Lioobayoyo
  • 156
  • 1
  • 7