There is a line containing a mathematical expression of the species:
1 / 3 + 2 / 3 is there a module that calculates the value of such expressions?
question@mail.ru
·
01.01.1970 03:00
There is a line containing a mathematical expression of the species:
1 / 3 + 2 / 3 is there a module that calculates the value of such expressions?
answer@mail.ru
·
01.01.1970 03:00
from the point of view of safety (as already said - with eval () you need to be very careful), performance and flexibility is better to use:
in [ 6 ]: import numexpr as nein [ 7 ]: ne.evaluate ( '' 1/3+2/3 ') out [ 7 ]: array ( 1.0 ) in [ 8 ]: var1 = 10 in [ 9 ]: var2 = 2 in [ 10 ]: ne.evaluate ( 'Var1 ** Var2' ) out [ 10 ]: array ( 100 , dtype = int32) he, by the way, is faster for more quickly complex calculations, supports the use of variables, supports Numpy, Scipy, etc.
maintains multi -flow calculations (using all available cores of the processor) and the VML from Intel (Vector Math Library, which is integrated into the Intel Math Keel Library (Mkl)) .
An example of working with the usual ("Vanilla python" ") with an array:
in [ 45 ]: lst = [ 1 , 2.718281828 ] in [ 46 ]: ne.evaluate ( 'log (lst)' ) out [ 46 ]: array ([ 0. , 1. ]) pre> with the Numpy Massion:
in [ 50 ]: a = np.array ([ 1 , 2.718281828 ]) in [ 51 ]: ne.evaluate ( 'log (a)' ) out [ 51 ]: array ([ 0. , 1. ]) pre> comparison of productivity with Numpy for an array consisting of the 1st million elements of the type numpy.float64 :
in [ 36 ]: a = np.random.rand ( 10 ** 6 ) in [ 37 ]: a.shapeout [ 37 ]: ( 1000000 ,) in [ 38 ]: len (a) out [ 38 ]: 1000000 in [ 39 ]: %timeit np.log (a) 10 loops, Best of 3 : 24.3 ms per loopin [ 40 ]: %timeyit ne.evaluate ( 'log (a)' ) 100 loops, Best of 3 : 5.45 ms per per Loopin [ 41 ]: %timeit np.sqrt (np.sin (a) ** 2 + np.cos (a) ** 2 ) 10 loops, Best of 3 : 84.5 ms per loopin [ 42 ]: %Timeit ne.evaluate ( 'sqrt (sin (a) ** 2 + cos (a) ** 2)' ) 100 loops, Best of 3 : 6.32 MS per loop PRE>