tags:

views:

64

answers:

4

Hi, If I define these variables:

double x0, xn, h;
int n;

and I have this mathematical expression:

h = (xn - x0)/n;

Is it necessary that I cast n into double prior doing the division for maximum accuracy like in

h = (xn - x0)/ (double) n;

I wrote a program to check the above but both expressions give the same answers. I understand that C will promote the integer to double type as variables xn and x0 are of type double but strangely enough in a book, the second expression with casting was emphasized.

My question would be if I'm thinking right.

Thanks a lot...

+1  A: 

No, this conversion is unnecessary because the numerator is a double. This promotes n to a double as well. The book probably mentions the explicit cast as a good habit, because if xn and x0 were ints then the expression would only use integer division.

rlbond
Thanks. Your answer is as good as the one that I've accepted but I had to make a choice.
yCalleecharan
+2  A: 

Your understanding is correct, and the book you read is either mistaken or being over-cautious (like people who claim that you should always test 0 == x instead of x == 0). The expression without the cast should always give precisely the same result as the expression with the cast.

Tyler McHenry
The cast is indeed unnecessary if at least one operand is already a `double`. However, it's easy to write `double f = 3 / 5`, and be quite surprised when `f` is always zero. I suspect the recommendation to always cast an integer argument in a floating point expression comes, at last in part, from the usual correct form of this: `double f = (double)3 / 5`.
Dale Hagglund
Thanks. In your case, we can also write f = 3./5 or f = 3/5. so as to enable floating point calculations.
yCalleecharan
A: 

It's unnecessary in this situation. It's typically needed in situations where you want a result that's different in type from the operands. A typical one is when doing timing. You often end up with code like: double(end_time-start_time)/CLOCKS_PER_SEC; In this case, the cast really is needed, because all the inputs are (typically) integer types, but you want a floating point result.

Jerry Coffin
Thanks. Your answer is as good as the one that I've accepted but I had to make a choice.
yCalleecharan
A: 

In C, the precision of any expression is the same as the highest precision constant/variable involved in the expression.

Explicit Casts are useful:

  • As a precaution.

Tomorrow you may edit the variables in the expression to use ints. A cast would still return the proper value

  • As a guide.

Someone else refering/modfiying ur code will easily understand that U are using a double.

i.e. "Let Ur code be its own comment !!"

CVS-2600Hertz
Thanks for your comments.
yCalleecharan