0

I need to solve some mathematical equations, something like below (but each time different formula):

formula="(2/10^8*x^2)+0.0131*x-1017.3-30"

where x is an integer.

I used eval() function to solve the problem. Function gave me an exception of:

TypeError: unsupported operand type(s) for ^: 'float' and 'int'

I solved it like this:

formula=formula.replace('^','**') 

Now, I encountered with another problem.

eval("2/10") 

returns 0 instead I need 0.2, as a result I get a wrong outcome. I appreciate for any answer.

1
  • 2
    btw you do know ^ is for bitwise XOR Commented Apr 30, 2013 at 12:04

1 Answer 1

3

Well, in Python 2.x int / int always returns an integer. Use Python 3 or explicitly write one of the arguments as a float, e.g. 2.0 / 10, or (as Marjin Pieters reminds us), import the explicit Py3-like division behaviour as: from __future__ import division.

Sign up to request clarification or add additional context in comments.

3 Comments

Or add from __future__ import division.
@MartijnPieters Indeed, thanks for mentioning, I always tend to forget that :)
@BasicWolf nvm I didn't see the second example. and he said x was an integer, but he must've lied. eg. >>> x=5 >>> formula="(2/10^8*x^2)+0.0131*x-1017.3-30" >>> eval(formula) -1005.2344999999999 In Python 3 that doesn't work, anyway that's what I thought, when I saw the second example I realised OP lied

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.