Search code examples
pythonnumpympmath

How to evaluate a numpy array inside an mpmath fuction?


I get an error when I try to use a numpy array inside mpmath function, this example fails when it reaches the line:

C = (f*L/D) + 2*mp.log(P1/P2)

Where P1 is an array. With the error:

cannot create mpf from array([**P1_array**])

I'm aware of this and this treads, which are related. But I cant get my code to work. Can someone help me to correct this mistake?

import numpy as np
import mpmath as mp

mp.mp.dps = 20

# State equation --> pV = nZRT

P1 = np.linspace(101325,10*101325,100)
P2 = 101325
T  = 300
D = 0.0095
A = mp.power(D,2)*mp.pi/4
L = 300
R = 8.31446
f = 0.05
Z1 = 0.9992
Z2 = 0.9999
Zm = 0.5*(Z1+Z2)

C = (f*L/D) + 2*mp.log(P1/P2)
w2 = (mp.power(P1,2)-mp.power(P2,2))*mp.power(A,2)/(Zm*R*T*C)
w = mp.power(w2,0.5)

Solution

  • You'll need to broadcast the function you want (log and power here) on your numpy array using np.frompyfunc:

    import numpy as np
    import mpmath as mp
    
    mp.mp.dps = 20
    
    # State equation --> pV = nZRT
    
    P1 = np.linspace(101325,10*101325,100)
    P2 = 101325
    T  = 300
    D = 0.0095
    A = mp.power(D,2)*mp.pi/4
    L = 300
    R = 8.31446
    f = 0.05
    Z1 = 0.9992
    Z2 = 0.9999
    Zm = 0.5*(Z1+Z2)
    
    log_array = np.frompyfunc(mp.log, 1, 1) #to evaluate mpmath log function on a numpy array
    pow_array = np.frompyfunc(mp.power, 2, 1) #to evaluate mpmath power function on a numpy array
    
    C = (f*L/D) + 2*log_array(P1/P2)
    w2 = (pow_array(P1,2)-pow_array(P2,2))*pow_array(A,2)/(Zm*R*T*C)
    w = pow_array(w2,0.5)