When eval an equation does it follow the PEMDAS rules?

For example: 2.0-1.0-3.0*6.0+5.0*4.0 when evaluated equals 3.0 when evaluated by python. To me that doesn't seem correct, I get a much larger number than 3.0

When I evaluate in python eval("6/2*3") it should equal 1 but in python it equals 9.

So anyone give me an idea on how to get eval to follow the PEMDAS rules?

Recommended Answers

All 4 Replies

When eval an equation does it follow the PEMDAS rules?

For example: 2.0-1.0-3.0*6.0+5.0*4.0 when evaluated equals 3.0 when evaluated by python. To me that doesn't seem correct, I get a much larger number than 3.0

When I evaluate in python eval("6/2*3") it should equal 1 but in python it equals 9.

So anyone give me an idea on how to get eval to follow the PEMDAS rules?

It does follow PEMDAS rules.
Never doubt Python's adherence to math rules.
6/2*3 equals 9 on:

  • Python (Any Version)
  • My TI-89 Graphing Calculator
  • My Mental Math

:D
that is because PEMDAS works like this: P, E, M and D, A and S So according to PEMDAS:
6/2*3

is(6/2)*3

That's because multiplication and division are the same rank.

Read more here.


Also, you stated that 2 - 1 - 3 * 6 + 5 * 4 = 3 according to Python.
That's absolutely correct.

  1. 2 - 1 - 3 * 6 + 5 * 4 (original problem)
  2. = 2 - 1 - 18 + 5 * 4 (1st multiplication is done)
  3. = 2 - 1 - 18 + 20 (2nd multiplication is done)
  4. = 1 - 18 + 20 (1st subtraction is done)
  5. = -17 + 20 (2nd subtraction is done)
  6. = 3 (addition is done)

Face palm!

Thank you again!

Please Excuse My Drunk Aunt Sally

As a side not, ask someone what 2+2*2 equals. Most people will say 8 instead of 6 lol. I've even got my teachers with it lol.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.