繁体   English   中英

matplotlib plot 显示不必要的对角线

[英]matplotlib plot shows an unnecessary diagonal line

So I'm trying to plot the approximation of an equation using Euler's method, and it works, the only problem is that the plot shows a diagonal line from the first point to the last, when I use a symbol to plot '<' ,这条线不见了,但我需要一条连续的线。

from decimal import *
#The Decimals are so that x is precise
from matplotlib import pyplot as pyplot

#Creates a range but with floats
def rangoFloat(m,maximo,cre): 
    minimo=Decimal(m)
    n=str(cre)
    while minimo <= maximo:
        yield float(minimo)
        minimo += Decimal(n)

#Substracs xn and delta
def ant(xn,delta): 
    return (float(Decimal(xn)-Decimal(delta)))


#Main function
def Teuler(x0,y0,A,B,cre=0.1,limite=20,delta=5,arr=([],[])): 
    y1=float(y0)
    arr[0].append(x0)
    arr[1].append(y0)
    for i in rangoFloat(ant(x0,-cre),limite,cre):

        arr[0].append(i)
        y1=float(Decimal(y1) * (Decimal(1) + Decimal(cre) * Decimal(A) - Decimal(cre) * Decimal(B)))
        arr[1].append(y1)
        
    return arr

当我运行下一个图时,会出现对角线

t1=Teuler(0, 1, 0.1, 0.16524,0.1,240)
t01 = Teuler(0, 1, 0.1, 0.16524,0.1,240)
t001=Teuler(0, 1, 0.1, 0.16524,0.01,240)
t0005= Teuler(0, 1, 0.1, 0.16524,0.0005,240)
pyplot.grid()
pyplot.plot(t1[0],t1[1])
pyplot.plot(t01[0], t01[1])
pyplot.plot(t001[0], t001[1])
pyplot.plot(t0005[0], t0005[1])
pyplot.show()

我正在使用 python 3.7

出现问题是因为您使用可变类型作为默认参数( ([],[]) )。 每个新的 function Teuler调用都会重用相同的 arrays。 您可以通过在Teuler的开头添加print语句来查看它:

print('arr length: ', len(arr[0]), len(arr[0]))

调用后:

t1=Teuler(0, 1, 0.1, 0.16524,0.1,240)
t01 = Teuler(0, 1, 0.1, 0.16524,0.1,240)
t001=Teuler(0, 1, 0.1, 0.16524,0.01,240)
t0005= Teuler(0, 1, 0.1, 0.16524,0.0005,240)
arr length:  0 0
arr length:  2400 2400
arr length:  4800 4800
arr length:  28800 28800

所以,你的t... arrays 从头开始多次,这就是对角线的证据。 您需要做的是是否将可变类显式传递为 arguments 或更改代码以防止 arrays 重用,例如:

#Main function
def Teuler(x0,y0,A,B,cre=0.1,limite=20,delta=5,arr=None):
    if arr is None:
        arr = ([],[])

如需进一步阅读,可以推荐Python 反模式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM