“只有大小为 1 的数组可以转换为 Python 标量”

H4Z*_*4RD 5 python math numpy matplotlib

我有这个代码:

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()
Run Code Online (Sandbox Code Playgroud)

并收到此错误:

类型错误:只有大小为 1 的数组可以转换为 Python 标量

我怎样才能解决这个问题?

Val*_*_Bo 4

您可以在单个变量 中计算与xy = math.sqrt(R**2 - (x - cc)**2)一样长的值,但在代码中,您尝试为x数组每个元素计算此表达式(并获取结果数组)。

为此,请按以下步骤操作:

  1. 将表达式定义为函数:

     def myFun(R, x, cc):
         return math.sqrt(R**2 - (x - cc)**2)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 定义该函数的向量化版本:

     myFn = np.vectorize(myFun, excluded=['R', 'cc'])
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将y计算为:

     y = myFn(R, x, cc)
    
    Run Code Online (Sandbox Code Playgroud)

对于R = 20.0,H = 30.0x = 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])
Run Code Online (Sandbox Code Playgroud)

  • 为什么不直接使用“np.sqrt(R**2 - (x-cc)**2)”? (4认同)