0

In my function:

const float EXPONENT = 1.8;
const uint8_t INDEX_MAX = 15;

uint8_t calcNewValue(uint8_t pwmIndex){
   uint8_t  pwmBaseValue = 255, result = 0;

   result = pow(pwmIndex, EXPONENT) / pow(INDEX_MAX, EXPONENT) * (pwmBaseValue);
   return result;   
}

When having a pwmIndex of 15 the "result" should read as: (15^1.8) / (15^1.8) * 255 resulting in 255. But I get 254 instead. Why?

Update: I checked the code here and it should work but it somehow doesn't on my 8 bit microcontroller.

Creatronik
  • 189
  • 3
  • 18
  • 1
    probably because of this: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – yano Jan 30 '17 at 20:04
  • `When having a pwmIndex of 15 the "result" should read as: (15^1.8) / (15^1.8) * 255 resulting in 255` - why??? It should be (15^1.8) / (255^1.8) * 255 resulting in 1. – barak manos Jan 30 '17 at 20:09
  • @barak because it's 255*1 because dividing one value by itself equals 1 – Creatronik Jan 30 '17 at 20:11
  • No it's not: `pwmIndex == 15 != 255 == INDEX_MAX`!!! – barak manos Jan 30 '17 at 20:11
  • 1
    It does not help mixing `float` with `double`. Please use `double` unless there is very good reason not to. You don't use `short` for small integers do you? But, this won't solve the problems, because floating point is a trade-off between range and precision. – Weather Vane Jan 30 '17 at 20:12
  • @barak my fault, that constant should've been 15 as well. – Creatronik Jan 30 '17 at 20:14
  • @WeatherVane where am I mixing float with double? I updated my question with a link. It works there, but why not in my application? – Creatronik Jan 30 '17 at 20:39
  • 1
    The value 1.8 is `double` which is assigned to `float` so there is the first opportunity for inaccuracy (2 conversions, the first is `1.8` text to `double` the second is `double` to `float`). Also the arguments and return value from `pow` are `double`. You edited the question to mention *8 bit microcontroller* after I made that comment, perhaps it does not implement `double`. – Weather Vane Jan 30 '17 at 20:47

0 Answers0