cancel
Showing results for 
Search instead for 
Did you mean: 

Double (or float) division does not work

JR2963
Senior II

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

11 REPLIES 11
S.Ma
Principal
  1. freq = ( (double) (odr) )/1000;

freq = (double)odr / 1000.0:​

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

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

S.Ma
Principal

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

S.Ma
Principal

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

KiptonM
Lead

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.

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 Venmo
Up vote any posts that you find helpful, it shows what's working..
S.Ma
Principal

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
Chief II

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.