我創建了一個非常簡單的 MWE 來說明我的問題。當我輸入時y**(2),程式運行。但是當我輸入sin(y)or 時cos(y),它會導致錯誤TypeError: can't convert expression to float。我將在下面討論修復此錯誤的嘗試。
from vpython import *
from scipy.optimize import fsolve
import math
import numpy as np
import sympy as sp
from sympy import Eq, Symbol, solve
import matplotlib.pyplot as plt
y = Symbol('y')
i = input()
i = ''.join(i).split(',')
for x in range(0, len(i)):
i[x] = i[x].strip()
userMediums = i
def refIndexSize(medium):
def refractiveProfile(y):
return eval(medium, {'y': y, 'np': np})
lowerProfile = Eq(eval(medium), 1)
upperProfile = Eq(eval(medium), 1.6)
bounds = [abs(round(float(solve(lowerProfile)[0]),5)),
abs(round(float(solve(upperProfile)[0]),5))]
lowerBound = np.amin(bounds)
upperBound = np.amax(bounds)
return lowerProfile
refIndexSize(userMediums[0])
錯誤:
sin(y) 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_48/825631216.py in <module>
29 return lowerProfile
30
---> 31 refIndexSize(userMediums[0])
/tmp/ipykernel_48/825631216.py in refIndexSize(medium)
20 return eval(medium, {'y': y, 'np': np})
21
---> 22 lowerProfile = eval(medium)
23 upperProfile = Eq(eval(medium), 1.6)
24 bounds = [abs(round(float(solve(lowerProfile)[0]),5)),
<string> in <module>
/srv/conda/envs/notebook/lib/python3.7/site-packages/sympy/core/expr.py in __float__(self)
357 if result.is_number and result.as_real_imag()[1]:
358 raise TypeError("can't convert complex to float")
--> 359 raise TypeError("can't convert expression to float")
360
361 def __complex__(self):
TypeError: can't convert expression to float
我查看了有關 的其他問題TypeError: can't convert expression to float,例如this和this。因此,我嘗試更改匯入的順序,盡管我無法更改通配符from vpython import *,因為它是匯入 vpython(據我所知)的唯一方法,但這不起作用。sp.sin(y)在查看不同的 SO 答案后,我也嘗試輸入,但這也無濟于事。再次,任何提示或幫助表示贊賞。
uj5u.com熱心網友回復:
你的問題在于這一行:
bounds = [abs(round(float(solve(lowerProfile)[0]),5)),
abs(round(float(solve(upperProfile)[0]),5))]
具體這部分:
abs(round(float(solve(upperProfile)[0]),5))
這里solve()函式以串列形式回傳復雜的解決方案。看到這個:
[1.5707963267949 - 1.04696791500319*I, 1.5707963267949 1.04696791500319*I]
因此,當您選擇 0 索引時,它將是一個復雜的結果,如下所示:
1.5707963267949 - 1.04696791500319*I
因此,您正在嘗試轉換float()為導致錯誤的解決方案。相反,您可以通過使用try-except像這樣的塊來洗掉具有復雜結果的解決方案的邊界:
try:
bounds = [abs(round(float(solve(lowerProfile)[0]),5)),
abs(round(float(solve(upperProfile)[0]),5))]
lowerBound = np.amin(bounds)
upperBound = np.amax(bounds)
except:
print("The solutions are complex. Cant find a result")
也像這樣匯入:
from vpython import *
from scipy.optimize import fsolve
import math
import numpy as np
import sympy as sp
from sympy import *
import matplotlib.pyplot as plt
uj5u.com熱心網友回復:
在ipython會話中,最相關的匯入:
In [1]: import numpy as np
...: import sympy as sp
...: from sympy import Eq, Symbol, solve
修改您的函式以回傳bounds。
In [2]: def refIndexSize(medium):
...:
...: def refractiveProfile(y):
...: return eval(medium, {'y': y, 'np': np})
...:
...: lowerProfile = Eq(eval(medium), 1)
...: upperProfile = Eq(eval(medium), 1.6)
...: bounds = [abs(round(float(solve(lowerProfile)[0]),5)),
...: abs(round(float(solve(upperProfile)[0]),5))]
...: lowerBound = np.amin(bounds)
...: upperBound = np.amax(bounds)
...:
...: return lowerProfile, bounds
...:
定義符號,并用字串呼叫函式。在互動式會話中,我不需要經歷input復雜的事情。
In [3]: y = sp.Symbol('y')
y**2 給出您在評論中宣告的界限:
In [4]: refIndexSize("y**(2)")
Out[4]: (Eq(y**2, 1), [1.0, 1.26491])
sin定義錯誤
使用sin運算式給出一個NameError. sin尚未匯入或定義。
In [5]: refIndexSize("sin(y) 1")
Traceback (most recent call last):
File "<ipython-input-5-30c99485bce7>", line 1, in <module>
refIndexSize("sin(y) 1")
File "<ipython-input-2-6fea36c332b7>", line 6, in refIndexSize
lowerProfile = Eq(eval(medium), 1)
File "<string>", line 1, in <module>
NameError: name 'sin' is not defined
sin從匯入math給你的錯誤:
In [6]: from math import sin
In [7]: refIndexSize("sin(y) 1")
Traceback (most recent call last):
File "<ipython-input-7-30c99485bce7>", line 1, in <module>
refIndexSize("sin(y) 1")
File "<ipython-input-2-6fea36c332b7>", line 6, in refIndexSize
lowerProfile = Eq(eval(medium), 1)
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.8/dist-packages/sympy/core/expr.py", line 359, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float
math.sin需要一個浮點值,因此不適用于符號y。
但是sin從匯入sympy,它可以作業:
In [8]: from sympy import sin
In [9]: refIndexSize("sin(y) 1")
Out[9]: (Eq(sin(y) 1, 1), [0.0, 0.6435])
由復數值引起的錯誤
最初您的問題顯示了使用sin(y),這給出了complex@Prakash 討論的錯誤
In [10]: refIndexSize("sin(y)")
Traceback (most recent call last):
File "<ipython-input-10-d470e7448a68>", line 1, in <module>
refIndexSize("sin(y)")
File "<ipython-input-2-6fea36c332b7>", line 9, in refIndexSize
abs(round(float(solve(upperProfile)[0]),5))]
File "/usr/local/lib/python3.8/dist-packages/sympy/core/expr.py", line 358, in __float__
raise TypeError("can't convert complex to float")
TypeError: can't convert complex to float
讓我們簡化您的功能以擺脫float似乎有問題的呼叫
In [11]: def refIndexSize(medium):
...: lowerProfile = Eq(eval(medium), 1)
...: upperProfile = Eq(eval(medium), 1.6)
...: bounds = [solve(lowerProfile),
...: solve(upperProfile)]
...: return lowerProfile, bounds
...:
繼續運行sin(y) 1),我們[0.0, 0.6435]像以前一樣得到值:
In [12]: refIndexSize("sin(y) 1")
Out[12]: (Eq(sin(y) 1, 1), [[0, pi], [0.643501108793284, 2.49809154479651]])
繼續運行sin(y),我們看到“原始”邊界包括復數值:
In [13]: refIndexSize("sin(y)")
Out[13]:
(Eq(sin(y), 1),
[[pi/2],
[1.5707963267949 - 1.04696791500319*I,
1.5707963267949 1.04696791500319*I]])
如果您真的需要從這樣的答案中得到一個圓整的浮點數,您需要先提取該real部分,或者abs先使用:
In [15]: bounds = _[1][1]
In [17]: abs(bounds[0])
Out[17]: 1.88773486361789
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403512.html
標籤:
上一篇:從陣列中洗掉多個元素
