writing mathematical operations in C

Hi guys

I started C programming today, so this is a super simple question...

When writing mathematical operations, how do you use parenthesis () to make sure the operations are made in the right order?

The equation I want to write would be, in mathematical language,

x1 = x0 - (x0 * x0 * x0 - 3) / (3 * x * x)

where x0 is the initial value of x and x1 is the new value we are after.

So far in C, I am writing

x = x - (x*x*x - 3) / (3*x*x);

but this does not seem to give the proper result (e.g., if x0 = 1, I shoulg get x1 = 1.666667).

Why?

Thanks

Re: writing mathematical operations in C

Quote:

*Originally posted by p_s_ross *

x = x - (x*x*x - 3) / (3*x*x);

Based on your equation and the fact you seem to have gotten a correct answer, you were lucky.

The reason you use parens it to make sure your equation is processed correctly. Various ways your equations could be parsed:

x = x - (x*x*(x - 3)) / (3*x*x);

x = x - (x*((x*x) - 3)) / (3*x*x);

x = (x - (x*x*(x - 3))) / (3*x*x);

each of which will give different results

You happen to want

x = x - (((x*x*x) - 3)) / (3*x*x));

which without parens C will process correctly.

Look into operator hierarchy and use more parens to force the equation you want. It also makes the equation easier to figure out 3 months from now.