Unpredictable Math -- Can't Divide Long Ints???

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

Unpredictable Math -- Can't Divide Long Ints???

2,789 次查看
mel
Contributor I
This is making me insane.  I am trying to divide a long by a constant and I can't get the compiler to do it.
 
unsigned int do_math(ulong long_speed)
{
 ulong pulsetime = (long_speed/1000L);
  
  
  pulsetime = (1000L/pulsetime);
 pulsetime /= DEF_INT_RATE;  // interupt rate
 
  return  (uint)pulsetime;
 
}
 
If the value of long_speed = 5000L, the first equation results  in pulsetime = 968.  Since when does 5000/1000 = 968???.  What can I do to get the math to work?  I already tried doubling the stack.
I tried making the 1000 1000.0.  I tried way too many things just to get a very simple division to work.
Does anyone have a clue?  Is there a codewarrior compiler guru out there? 
 
标签 (1)
0 项奖励
回复
2 回复数

735 次查看
Marreshe
Contributor I
 
If the value of long_speed = 5000L, the first equation results  in pulsetime = 968.  Since when does 5000/1000 = 968???.  What can I do to get the math to work?  I already tried doubling the stack.
I tried making the 1000 1000.0.  I tried way too many things just to get a very simple division to work.
Does anyone have a clue?  Is there a codewarrior compiler guru out there? 
 
I agree you should probably take a look at the assembly.  Is DEF_INT_RATE a #define?  This maybe part of the problem.  The reason is you are casting pulsetime as a uint on the return...this could cause some unwanted optimization.  First try a #pragma around the function to turn off optimization and make sure DEF_INT_RATE is a const ulong not a #define.  You might also try returning pulsetime as a ulong rather than a uint to see what is going on. 
 
If you can you might want to bit shift rather than divide...roundoff errors can be murderous.
0 项奖励
回复

735 次查看
CompilerGuru
NXP Employee
NXP Employee
as I don't see the problem, so just some questions and hints.
- The "1000L/pulsetime" could be a division by zero, you should handle this case, I guess.
- well, as long as it does not work, its not so important, but it looks like everything except the first division could be performed with (unsigned) int arithmetic.
- for which target/cpu is this? Which tools do you use?
- can you provide a complete compilable source code, possibly with the disassembly listing and with one usage which fails?
(what is DEF_INT_RATE?)
- are you sure this is a functional problem and not a debug info only problem?
- check the preprocessor output. Does not look like this is your problem, but in the end you never know.

Daniel
0 项奖励
回复