Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: eval() that coerces values to floating point?

Tags:

python

eval

Is there a way to execute an eval-like function that coerces its values to floating point? I am hoping to

eval('1/3')

and have it return the floating point value .333333 rather than the integer value 0.

like image 891
Mark Harrison Avatar asked Feb 23 '12 05:02

Mark Harrison


People also ask

What does eval () do in Python?

Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.

How do you convert data to float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

What is the use of eval () method in List explain with an example?

Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.

What is eval () in Python and can we perform mathematical operations using eval function give an example?

The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.


2 Answers

Grab the compiler flag for __future__.division, pass it and your code to compile(), then run eval() on the returned code object.

(note by mh) This has the added advantage of not changing the division operation globally, which might have unexpected side effects. (end note)

>>> import __future__
>>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))
0.33333333333333331
like image 181
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 16:09

Ignacio Vazquez-Abrams


You question is really: how can I get Python to do floating point division by default. The answer is:

from __future__ import division
like image 40
kindall Avatar answered Sep 30 '22 15:09

kindall