I have code written in C which is intended for a 16-bit microcontroller. The code essentially does lot of floating point arithmetic.
The arithmetic works fine till the result is positive, but in case of subtraction, if the expected result is negative, I get a zero.
result = 0.005 - 0.001; Is correctly computed as 0.004
result = 0.001 - 0.005; Is always zero.
Why is there such a behavior for float?
Interesting. It could quite easily be a fault in the floating point software. Embedded systems often include floating point as an option so as to keep the code size down.
I’m not sure that’s the problem here though since your first statement works.
What happens with:
The idea here is to collect useful information as to what could be causing it, a common thing to do in forensics. The results of those calculations are likely to be helpful in determining the actual problem.
Based on your results in the comments:
It looks like your floating point library has a serious shortcoming. Two more questions:
There may be some problem with the way you’re printing or it may be a limitation of your environment.
Ajit, I think you’re really going to have to give us some code to help you out. Not necessarily your real code (your concern about releasing the real code is understood), just some that demonstrates the problem.
Based on some of your comments, to wit:
I’m not sure I totally understand, but I’ll give it a shot.
You have a 32-bit float, for example, -0.003 and you multiply it by 1000 and put it in an integer (0xFFFD is the 16-bit two’s complement representation of -3). So what happens when you run something like the following code:
The reason I want you to test an integer is that it may have nothing to do with floats at all. It may be that the float value is perfectly correct, but there’s some problem with the way you’re printing it (the CAN method).
If “CAN” is some sort of serial interface, it may be there’s a restriction on the bytes you’re allowed to send across it. I can envisage a scenario where the high bytes are used as packet markers so that FF may actually end the message prematurely. That’s why I also want you to test -32768 (0x8000).
It’s hard to believe that STMicroelectronics would produce such a braindead runtime system that it couldn’t handle negative floats. It seems much more likely to me that the information is being corrupted somewhere else (for example, the “printing” process, whatever that may be).