Python Forum

Full Version: Coding a formula
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I'm learning python, and have an exercise to do in order to practice bracketing operators. The exercise is to code the following formula:


3x3 – 2x2 + 3x - 1

with x being either 0, 1, or -1.

assign the result to y.

The problem:

The values of y (according to the exercise) should then be:

if x=0 then y is -1

if x = 1 then y is 3.0

if x = -1 then y is -9.0

However, my results are:

results:

0 -> -1.0
1 -> 25.0
-1 -> -35.0

My code

x = 0

x = float(x)

y = (((3*x) ** 3) - ((2*x) ** 2) + ((3 * x) - 1))


print (x)

print (y)
Clearly something is not quite correct. I've broken the formula down into steps in code, and also worked it through on paper. I'm getting the same results.

Is the exercise correct or is my code off? Please help with suggestions / corrections!

Many thanks
The problem is order of precedence. 3x3 would properly be coded 3*x**3 or 3*x*x*x
You are coding 3x, cubed rather than 3 times x cubed.

Same with the square. Fix those and you will have right answer (or repost)
Perfect, got it working.

Thanks for your very useful input.