This might be dumb... but I'm having problems raising e to a negative number and I can't figure out what is going on.

>>> math.exp(((-23*(23-1))/730))
0.36787944117144233
>>> math.exp(-506/730)
0.36787944117144233
>>> math.exp(-.69)
0.5015760690660556
>>> math.exp(-(506/730))
1.0

For some reason I keep getting different answers when they should all be the same...
(506/730 is about 0.69)
Does anyone know what's happening?

Thanks!

Dani AI

Generated

Short answer: the different results come from integer-division quirks in older Python plus where the minus sign ends up. As suggested, this is a division/type issue; 's float hint also points to the usual fix. The differing outputs are not a math.exp bug.

When both operands are integers, Python 2's plain / yields an integer result (the fractional part is discarded and negative quotients round down). That means 506/730 produces 0 while -506/730 (parsed as (-506)/730) yields -1. Because of that parsing difference, the same-looking expressions can evaluate to exp(-1) (about 0.3679), exp(0) (1.0) or exp(-0.69) (about 0.5).

Practical fixes and debugging tips:

  • Force floating-point division by converting one operand to float (for example with float() or a float literal) so the quotient is the expected ~0.693.
  • Run under Python 3 (where / returns a float) or enable true-division behavior in Python 2 if you must keep 2.x.
  • When results surprise you, print the intermediate value and its type (and check your Python major version via sys.version_info) to see whether you have an integer or float before calling math.exp.

For background and exact semantics see the division discussion in Python standards (PEP 238) and the language reference on arithmetic operations:
PEP 238 — Changing the Division Operator
Python 3 reference — binary arithmetic operations

Recommended Answers

All 3 Replies

Maybe you are using Python 2, where integer division 506/730 makes 0, when you do not want that but actually 506.0/730 float division?

Better to get used to write in beginning of your programs:

from __future__ import division

So you get what you expect and must use // for integer division instead of single /

Another way is to add '.' behind the integer to make it a 'float'.

506/730

to

506./730

This might be dumb... but I'm having problems raising e to a negative number and I can't figure out what is going on.

>>> math.exp(((-23*(23-1))/730))
0.36787944117144233
>>> math.exp(-506/730)
0.36787944117144233
>>> math.exp(-.69)
0.5015760690660556
>>> math.exp(-(506/730))
1.0

For some reason I keep getting different answers when they should all be the same...
(506/730 is about 0.69)
Does anyone know what's happening?

Thanks!

Thank you so much! I didn't realize it was that sensitive.

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.