2022-12-16 01:14 AM
Hi,
on STM32H7 I want to divide 25600/1000 - I get always result = 25. Why? What I do wrong?
double freq;
int odr=25600;
freq = (double) (odr)/1000;
Thank you
2022-12-16 01:51 AM
2022-12-16 03:06 AM
freq = (double)odr / 1000.0:
2022-12-16 03:49 AM
unfortunatelly does not work .. I tried a lot of combination like (double)odr/(double(1000)) ...
2022-12-16 03:54 AM
How do you read the variable value? That could be the issue. Or project properties, compiler or linker.
2022-12-16 03:56 AM
Use debug mode, breakpoint, watch variable. Make the variable global if needed.
2022-12-16 08:05 AM
I just did your original one and it worked. freq was 25.600000000000001 in the debugger.
Personally, unless you were using odr for something else I would have made it a double also.
But in any case, for me, the safest way so I never have problems or questions is:
freq = ((double) odr) / 1000.0;
The 1000.0 should default as a double.
And parenthesis do not cost anything in run time.
2022-12-16 09:26 AM
How are you printing / inspecting the output?
Can you print the two 32-bit words that are in the resulting double?
What compiler/version are you using?
What libraries is that pulling in?
void float_test(void)
{
double freq1, freq2;
int odr=25600;
uint32_t *q = (uint32_t *)&freq1;
freq1 = (double)odr / 1000.0;
freq2 = (double)odr * 1e-3;
printf("%lf %lf\n", freq1, freq2);
printf("%08X %08X\n", q[0], q[1]);
}
25.600000 25.600000
9999999A 40399999
2022-12-17 09:18 PM
One more thing. The test code may be compiler optimised and the division result compiler calculated. When you test a code, use global variables, so you can see their name on the debugger watch window, and if your code has a loop, you can stip amd change the values without rebuilding the program...
2022-12-18 02:43 PM
The code in the topic is correct. Also it is trivial and there is no need to "test" it. Therefore the problem is somewhere else. For example, the actual code is missing the cast to double type or uses some other intermediate variable.