"只能将size-1数组转换为Python标量& quot; [英] "Only size-1 arrays can be converted to Python scalars"

查看:50
本文介绍了"只能将size-1数组转换为Python标量& quot;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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标量

TypeError: only size-1 arrays can be converted to Python scalars

我该如何解决?

推荐答案

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

You can compute y = math.sqrt(R**2 - (x - cc)**2) as long as x in a single variable, but in your code you attempt to compute this expression for each element of x array (and get an array of results).

为此,请按照下列步骤操作:

To to this, proceed as follows:

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

  1. Define your expression as a function:

 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)(较短的数组))我知道了:

    For R = 20.0, H = 30.0 and x = np.linspace(-5,5,10) (a shorter array) I got:

    array([ 8.22875656, 10.34341406, 11.99128261, 13.34639903, 14.49112624,
           15.47223243, 16.31925481, 17.05218586, 17.6852162 , 18.22875656])
    

    这篇关于"只能将size-1数组转换为Python标量& quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆