绘制函数时如何解决绘图错误?

时间:2019-07-25 18:26:26

标签: python matplotlib

因此程序将一个函数转换为泰勒多项式。下一部分是它采用您指定的函数,我正在执行sp.exp(x),并将其与泰勒多项式一起绘制。但是我的代码说尺寸必须一致。通常,您可以通过函数来​​绘制范围,它将在该范围内进行绘制,但是在这里不起作用。

我被告知要制作一个单独的列表,然后将其绘制出来,但是我想找到另一种方法。另外,如果我这样做了,我会努力地列出该清单。

import numpy as np
from sympy import *
import math as mt
import matplotlib.pyplot as plt

################################################

def factorial(m):
    if m <= 0:
        return 1
    else:
        return m*factorial(m-1)

x, h = symbols('x, h')
f = Function('f')

                    ##Factorial

################################################

def fp(function, m = 10, c = 0, x0 = 1):

    if m < 0 or type(m) != int:
        raise ValueError('Value m must be a positive integer', m)


    if type(c) not in (int, float):

        raise ValueError('Value c must be one a Real Number', c)

                    ##Error Messages

################################################

    i = 0 
    p = 0

    while i <= m:
        p = p +(((function.diff(x, i).subs(x,c))/(factorial(i)))*(x-c)**i)
        i += 1
    print(p)

                    ## Defin Taylor

################################################

    par = 1/1000
    r = np.arange(-10, 10)
    plt.plot(r, function.subs(x, r), 'black')
    plt.plot(r, p(r), 'blue')
    plt.show()


## Plots function

错误消息

Traceback (most recent call last):
  File "<pyshell#120>", line 1, in <module>
    fp.fp(sp.exp(x))
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\FinalPartTwo.py", line 49, in fp
    plt.plot(r, function.subs(x, r), 'black')
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\pyplot.py", line 2795, in plot
    is not None else {}), **kwargs)
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_axes.py", line 1666, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_base.py", line 225, in __call__
    yield from self._plot_args(this, kwargs)
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_base.py", line 391, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\axes\_base.py", line 270, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (20,) and (1,)

0 个答案:

没有答案