I'm trying to run the following code but an error appears at the line with S[i][0]
.
TypeError: can't convert expression to float
I'm am sure that my variables D[][]
, h[]
, age[]
, A[]
, B[]
and n
are ok (they are floats). I think it has something to do with the symbolic figure x
.
At the end, S
is supposed to be a (7,1) vector of polynomes.
import numpy as np
import sympy as sp
age = np.arange(15,55,5)
N = np.array([0, 7.442, 26.703, 41.635, 49.785, 50.209, 50.226])
n = len(N)
h = np.zeros(n)
for i in range(n) :
h[i] = age[i+1] - age[i]
mu = np.zeros(n)
lamda = np.zeros(n)
F = np.zeros((n,1))
A = np.zeros(n)
B = np.zeros(n)
for i in range(n) :
mu[i] = h[i-1]/(h[i]+h[i-1])
lamda[i] = h[i]/(h[i]+h[i-1])
F[i][0] = (6*(N[i]*h[i-1] - h[i]*N[i-1]))/((h[i]+h[i-1])*h[i]*h[i-1])
M = 2*np.eye(n,n) + 0.5*np.diag(np.ones((n-1)),1)+ 0.5*np.diag(np.ones((n-1)),1).T
D = np.dot(np.linalg.inv(M),F)
for i in range(n-1) :
A[i] = (N[i+1] - N[i])/h[i] - (h[i]*(D[i+1][0] - D[i][0]))/6
B[i] = N[i] - (((h[i])**2)*D[i][0])/6
def s(D, h, age, A, B, n) :
S = np.zeros((n,1))
x = sp.Symbol("x")
for i in range(n) :
S[i][0] = (D[i+1][0]*((x - age[i])**3))/(6*h[i]) - (D[i][0]*((x - age[i+1])**3))/(6*h[i]) + (A[i])*(x - age[i]) + B[i]
return sp.simplify(S)
S = s(D, h, age, A, B, n)
The problem is that while most of your variables are floats, x
is symbolic, which causes all of those calculations in the end to be a symbolic object. Such objects are handled at python-level with classes, while numpy requires numbers, so it tries to apply float()
to it. For example,
>> float(sp.Add(1, 1))
2.0
>> float(s.Add(1 + x))
Traceback (most recent call last):
File "<pyshell#85>", line 1, in <module>
float(sp.Add(1, x))
File "C:\Users\ip507\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\core\expr.py", line 239, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float
Since you don't intend to use an calcuations with the "array-like" S
object, it can just be a list, where you collect the expressions.
def s(D, h, age, A, B, n):
x = sp.Symbol("x")
S = []
for i in range(n):
S.append((D[i+1][0]*((x - age[i])**3))/(6*h[i]) - (D[i][0]*((x - age[i+1])**3))/(6*h[i]) + (A[i])*(x - age[i]) + B[i])
return S
Having said that, you have an error which causes an IndexError
. D
has a shape of (7, 1), but you call D[i+1]
. It's something you'll need to address since I don't know your intentions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.