Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coding a formula
#1
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
Reply
#2
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)
Reply
#3
Perfect, got it working.

Thanks for your very useful input.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python “Formula” Package: How do I parse Excel formula with a range of cells? JaneTan 1 2,639 Jul-12-2021, 11:09 AM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020