Hi I have been trying to use the equation:
int Temp; Temp = 680*((N-82)/(920-82)); return Temp;
Assuming 'N' is an int, the subexpression ((N-82)/(920-82)) yields 0 for any value of 'N' less than 920. 680 * 0 = 0. You are using integer arithmetic, you know.
Your examples end up with a fraction that is less than one so you should expect zero for the answer. You are looking for an integer result but your calculation would indicate you need to change this to floating point math.
"your calculation would indicate you need to change this to floating point maths" Or just pre-scale N by a suitable factor so that the result is non-zero!
Hi I have tried to use float point but I get zero...
int delay; float Temp; for(delay=82; delay < 920; delay += 20) { Temp= (delay-82)/(920-82); Temp = 680 * Temp; printf("result is %f\n", Temp); }
A Neil Do you have example of using scaling to solve my problem?
'delay' is an int, the RHS expression (delay-82)/(920-82) yields 0 for any value of 'delay' less than 920. 0 is converted to 0.0 for assignment to 'Temp'. 680 * 0.0 = 0.0. Try:
Temp= ((float)delay-82)/(920-82);
Scaling fixed point math takes some understanding. Perhaps you could start by reviewing this article or Google for fixed point math: http://www.wwnet.net/~stevelim/fixed.html Perhaps you should also review a "C" tutorial. If you want to perform floating point operations then you need to have your equation representative of a floating point calculation. So as Dan has suggested "cast" the divide operation or change your constants to be float values.
for(delay=82; delay < 920; delay += 20) { Temp = (delay-82.0)/(920.0-82.0); Temp = 680.0 * Temp; printf("result is %f\n", Temp); }
It's often possible to re-order the operations to avoid early truncation, without resorting to floating point. Temp = 680*((N-82)/(920-82)); is equivalent to t = N - 82; t = t / (920-82); Temp = 680 * t; The problem is in step 2, where t goes to zero. (Even when N > 920, there's a big loss of accuracy.) Algebraically, it doesn't matter whether you multiply or divide first. So moving the parens to force a different order of operation results in: Temp = (680*(N-82))/(920-82); is equivalent to t = N - 82; t = 680 * t; Temp = t / (920 - 82); The problem to watch out for here is the opposite of the truncation problem. "680 * t" might overflow, depending on the possible input range and size of integers used. Handling overflow is often easy, though -- just use a larger int for those steps -- compared to the expense of floating point or scaling fixed point results.
"Do you have example of using scaling to solve my problem?" See Drew's reply - use the multiplication by 680 to "scale" the numerator before doing the division!
Try this long Ralph INT Temp Ralph = 680*(N-82); Ralph /= (920-82)); Temp = (short) Ralph return (temp)