长度为 1 的数组可以转换为 python 标量错误吗?Python [英] Length-1 arrays can be converted to python scalars error? python
问题描述
from numpy import *
from pylab import *
from math import *
def LogisticMap(a,x):
return 4.*a*x*(1.-x)
def CosineMap(a,x):
return a*cos(x/(2.*pi))
def TentMap(a,x):
if x>= 0 or x<0.5:
return 2.*a*x
if x>=0.5 or x<=1.:
return 2.*a*(1.-x)
a = 0.98
N = 40
xaxis = arange(0.0,N,1.0)
Func = CosineMap
subplot(211)
title(str(Func.func_name) + ' at a=%g and its second iterate' %a)
ylabel('X(n+1)') # set y-axis label
plot(xaxis,Func(a,xaxis), 'g', antialiased=True)
subplot(212)
ylabel('X(n+1)') # set y-axis label
xlabel('X(n)') # set x-axis label
plot(xaxis,Func(a,Func(a,xaxis)), 'bo', antialiased=True)
我的程序应该采用三个定义的函数中的任何一个并绘制它.它们都从 0 到 N 的数组 xaxis 中获取值 x,然后返回该值.我希望它绘制 xaxis 与 f(xaxis) 的图形,其中 f 是上述三个函数中的任何一个.Logisticmap 函数工作正常,但对于 CosineMap,我收到错误只有长度为 1 的数组可以转换为 python 标量",而对于 TentMap,我收到错误具有多个元素的数组的真值不明确,请使用 a.any() 或 a.all()".如果 0<=x<0.5,我的帐篷地图函数假设返回 2*a*x,如果 0.5<=0<=1,它假设返回 2*a*(1-x).
My program is supposed to take any of the three defined functions and plot it. They all take in a value x from the array xaxis from 0 to N and then return the value. I want it to plot a graph of xaxis vs f(xaxis) with f being any of the three above functions. The logisticmap function works fine, but for CosineMap i get the error "only length-1 arrays can be converted to python scalars" and for TentMap i get error "The truth value of an array with more than one element is ambiguous, use a.any() or a.all()". My tent map function is suppose to return 2*a*x if 0<=x<0.5 and it's suppose to return 2*a*(1-x) if 0.5<=0<=1.
推荐答案
你先导入numpy.cos
,然后再导入math.cos
.后者掩盖了前者,并且不知道如何处理 NumPy 数组.因此出现错误.
You first import numpy.cos
, and then import math.cos
. The latter shadows the former, and doesn't know how to handle NumPy arrays. Hence the error.
要修复,请尝试:
import numpy
def CosineMap(a,x):
return a*numpy.cos(x/(2.*pi))
这类问题是避免 from X import *
样式导入的一个很好的理由.
Problems of this sort are a good reason to avoid from X import *
-style imports.
对于 TentMap
,这里是一种正确矢量化的方法:
As to TentMap
, here is one way to vectorize it correctly:
def TentMap(a,x):
return 2.*a*numpy.minimum(x, 1.-x)
这篇关于长度为 1 的数组可以转换为 python 标量错误吗?Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!