「サイズ1の配列のみをPythonスカラーに変換できます」
Aug 21 2020
私はこのコードを持っています:
R = float(input("Enter the arc's radius of curvature: "))
H = float(input("Enter the arc's height: "))
import matplotlib.pyplot as plt
import numpy as np
import math
#cc = center of curvature
cc = math.sqrt(R**2 - (H / 2)**2)
x = np.linspace(-5,5,100)
y = math.sqrt(R**2 - (x - cc)**2)
plt.plot(x, y, 'c')
plt.show()
このエラーが発生します:
TypeError:サイズ1の配列のみをPythonスカラーに変換できます
どうすればこれを修正できますか?
回答
1 Valdi_Bo Aug 21 2020 at 12:27
あなたは計算できるy = math.sqrt(R**2 - (x - cc)**2)
限りのxに単一の変数が、あなたのコードでは、あなたにはこの表現を計算しようとすると、各要素のXの 配列(および結果の配列を取得します)。
これを行うには、次の手順に従います。
式を関数として定義します。
def myFun(R, x, cc): return math.sqrt(R**2 - (x - cc)**2)
この関数のベクトル化されたバージョンを定義します。
myFn = np.vectorize(myFun, excluded=['R', 'cc'])
yを次のように計算します。
y = myFn(R, x, cc)
以下のためにR = 20.0
、H = 30.0
そしてx = np.linspace(-5,5,10)
(短い配列)私が得ました:
array([ 8.22875656, 10.34341406, 11.99128261, 13.34639903, 14.49112624,
15.47223243, 16.31925481, 17.05218586, 17.6852162 , 18.22875656])