Skip to main content
JR2963
Senior II
December 16, 2022
Question

Double (or float) division does not work

  • December 16, 2022
  • 8 replies
  • 2261 views

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

This topic has been closed for replies.

8 replies

S.Ma
Principal
December 16, 2022
  1. freq = ( (double) (odr) )/1000;

Tesla DeLorean
Guru
December 16, 2022

freq = (double)odr / 1000.0:​

Tips, Buy me a coffee, or three.. PayPal VenmoUp vote any posts that you find helpful, it shows what's working..
JR2963
JR2963Author
Senior II
December 16, 2022

unfortunatelly does not work .. I tried a lot of combination like (double)odr/(double(1000)) ...

Tesla DeLorean
Guru
December 16, 2022

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

Tips, Buy me a coffee, or three.. PayPal VenmoUp vote any posts that you find helpful, it shows what's working..
S.Ma
Principal
December 16, 2022

How do you read the variable value? That could be the issue. Or project properties, compiler or linker.

S.Ma
Principal
December 16, 2022

Use debug mode, breakpoint, watch variable. Make the variable global if needed.

KiptonM
Senior III
December 16, 2022

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.

S.Ma
Principal
December 18, 2022

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...

Piranha
Principal III
December 18, 2022

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.

S.Ma
Principal
December 19, 2022

One last thing, refrain from using float and double under interrupt.

Piranha
Principal III
December 20, 2022