Evaluate/calculate math equation with every entry in array

Viewed 116

I have an array and an equation.

I want to plug in all array values into the equation and save it.

What I've tried until now:

import math
import numpy as np

Z_F0=376.73
Epsilon=3.66

wl_range = [np.arange(0.1, 50, 0.1)]
wl_array = np.array(wl_range)
multiplied_array = 6+(2*math.pi*6)*math.exp(-1*(30.666/wl_array)**0.7528)
print(multiplied_array)

Or I've tried multiplied_array = np.vectorize(6+(2*math.pi*6)...)

But I get the

only size-1 arrays can be converted to Python scalars 

error.

2 Answers

You don't need math, numpy has pi and exp. pi would have worked with math, as it is just a constant. But the content of your exponential is a vector, so you need to use numpy for that.

There are situations where math is faster (when you don't vectorize), as numpy has higher overhead checking for the dimensions of your input.

import numpy as np

Z_F0=376.73
Epsilon=3.66

wl_range = [np.arange(0.1, 50, 0.1)]
wl_array = np.array(wl_range)
multiplied_array = 6+(2*np.pi*6)*np.exp(-1*(30.666/wl_array)**0.7528)
print(multiplied_array)

output:

[ 6.          6.          6.          6.          6.00000001  6.00000015
   6.00000127  6.00000656  6.00002459  6.00007283  6.00018111  6.00039369
   6.0007699   6.00138329  6.00231952  6.00367362  6.00554684  6.00804354
   6.01126831  6.01532348  6.020307    6.02631085  6.03341981  6.04171066
   6.0512517   6.06210249  6.07431393  6.08792837  6.10297998  6.11949516
   6.13749297  6.15698571  6.17797939  6.20047433  6.22446568  6.24994393
   6.27689541  6.30530278  6.33514546  6.36640006  6.39904075  6.43303963
   6.46836702  6.50499181  6.54288169  6.58200341  6.62232297  6.66380586
   6.70641722  6.75012196  6.79488494  6.84067111  6.88744554  6.93517359
   6.98382097  7.03335377  7.08373859  7.13494255  7.18693331  7.23967918
   7.29314908  7.34731259  7.40213999  7.45760222  7.51367097  7.5703186  ...

math.exp() only works with a scalar argument x. If you use numpy.exp() then the equation should work.

Related