【问题标题】:Can't Multiply Sequence By Non-Int of Type Float? Python不能将序列乘以浮点类型的非整数? Python
【发布时间】:2012-12-09 03:59:16
【问题描述】:

模块 OneDMaps:

def LogisticMap(a,nIts,x):
    for n in xrange(0,nIts):
        return 4.*a*x*(1.-x)

实际程序:

# Import plotting routines
from pylab import *
import OneDMaps 

def OneDMap(a,N,x,f):
    return x.append(f(a,N,x))

# Simulation parameters
# Control parameter of the map: A period-3 cycle
a = 0.98
# Set up an array of iterates and set the initital condition
x = [0.1]
# The number of iterations to generate
N = 100

#function name in OneDMaps module
func = LogisticMap

# Setup the plot
xlabel('Time step n') # set x-axis label
ylabel('x(n)') # set y-axis label
title(str(func) + ' at r= ' + str(a)) # set plot title

# Plot the time series: once with circles, once with lines
plot(OneDMap(a,N,x,func), 'ro', OneDMap(a,N,x,func) , 'b')  

该程序应该从模块 OneDMaps.py 中调用一个函数,然后根据它的迭代绘制它。我收到错误“无法将序列乘以浮点类型的非整数”,并且我尝试使用 LogisticMap(float(a)...) 但这不起作用。此外,我希望函数名称显示在绘图的标题中,但我得到“在 r=0.98 而不是说 LogisticMap at r=0.98.

【问题讨论】:

  • 那么,到底是什么问题呢?我似乎很清楚错误是什么。 "Can't multiply sequence by non-int of type float" - 这意味着你不能做4.*'s' 如果你只想乘法,请从4.*a*x*(1.-x) 中删除.

标签: python plot


【解决方案1】:

您像这样设置list

x = [0.1]

然后你将它乘以 float:

return 4.*a*x*(1.-x)

你不能那样做。也许您希望 x 成为 array 而不是 list

x = array([0.1])

(这将按元素进行乘法)


请注意,添加列表会连接:

[0] + [1] == [0, 1]

一个整数的乘法相当于串联那么多次:

[0] * 3 == [0, 0, 0]

但这对浮点数没有意义,

[0] * 3.0 #raises TypeError as you've seen

(例如,如果乘以 3.5 会得到什么?)

【讨论】:

  • +1 给你和 OP - 我不知道你可以这样定义浮点数:)
  • @RocketDonkey -- 以什么方式定义浮动?
  • 使用 4. 并省略 0 - 有道理但很酷。
  • @RocketDonkey -- 哦,我建议你使用额外的0 ... 3.0 而不是3.。它使阅读更容易。
  • 谢谢!解决了我的问题:)顺便说一句,我的标题代码有什么问题?它显示标题名称,但添加了“
猜你喜欢
  • 2015-06-27
  • 2011-04-06
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2013-09-11
相关资源
最近更新 更多