【问题标题】:"Only size-1 arrays can be converted to Python scalars"“只有大小为 1 的数组可以转换为 Python 标量”
【发布时间】:2020-08-21 02:56:20
【问题描述】:

我有这个代码:

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:只有 size-1 的数组可以转换为 Python 标量

我该如何解决这个问题?

【问题讨论】:

  • 为什么? python 标量只是一个数字。一个有 2 个数字的数组可以只转换为一个,可以吗?但是哪条线产生了错误? math.sqrt 仅适用于一个号码。但是x 是一个数组,所以R**2-(x-h)**2 也是一个数组。这是我对问题线的猜测。阅读math 文档。问题行中的测试值!做一些你自己的调试。
  • 是 y = 线。
  • @hpaulj:我在使用 polyfit(X,Y,Z,2) 时得到同样的错误,以获得二阶多项式回归。也许问题是指定哪个是因变量?

标签: python numpy matplotlib math


【解决方案1】:

你可以计算y = math.sqrt(R**2 - (x - cc)**2),只要xsingle 变量中,但在您的代码中您尝试计算 x array每个元素 的表达式(并获得一个数组 结果)。

为此,请执行以下操作:

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

     def myFun(R, x, cc):
         return math.sqrt(R**2 - (x - cc)**2)
    
  2. 定义此函数的矢量化版本:

     myFn = np.vectorize(myFun, excluded=['R', 'cc'])
    
  3. 计算 y 为:

     y = myFn(R, x, cc)
    

对于R = 20.0H = 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])

【讨论】:

  • 为什么不直接使用np.sqrt(R**2 - (x-cc)**2)
【解决方案2】:

我遇到了同样的问题/错误,帮助我的是 Stef 和 Nils Werner 的回答: Solving only size-1 arrays can be converted to Python scalars error

基本上,您不能将 .numpy.math 函数混合使用,因为它们需要不同的输入类型(数组或单个整数用于 numpy 函数,但只有单个整数用于数学函数)。

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 2021-10-17
    • 2018-07-22
    • 2021-07-08
    • 1970-01-01
    • 2021-06-24
    • 2021-06-20
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多