多项式图

时间:2018-10-02 15:50:34

标签: python numpy graph

在一些帮助下,我产生了以下代码。以下是给定输入的一些所需输出。但是,我在完成此代码的最后一个任务时遇到了一些麻烦。寻找有关此的帮助,非常感谢任何指导或帮助,谢谢!

enter image description here

flops = 0

def add(x1, x2):
    global flops
    flops += 1
    return x1 + x2

def multiply(x1, x2):
    global flops
    flops += 1
    return x1 * x2

def poly_horner(A, x):
    global flops
    flops = 0
    p = A[-1]
    i = len(A) - 2
    while i >= 0:
        p = add(multiply(p, x), A[i])
        i -= 1
    return p

def poly_naive(A, x):
    global flops
    p = 0
    flops = 0
    for i, a in enumerate(A):
        xp = 1
        for _ in range(i):
            xp = multiply(xp, x)
            p = add(p, multiply(xp, a))
    return p

鉴于以下输入,我得到了以下输出:

poly_horner([1,2,3,4,5], 2)
129
print(flops)
8
poly_naive([1,2,3,4,5, 2])
129
print(flops)[![enter image description here][1]][1]
20
np.polyval([5,4,3,2,1], 2)
129

1 个答案:

答案 0 :(得分:1)

我想您想创建一个图形,尽管您的问题很模糊……但是我的代码运行时有几分钟的时间要杀死。无论如何,看来您可能在绘图上有困难。

import numpy as np
import pylab as pl

x = np.arange(10)
y = x * np.pi

# you can calculate a line of best fit (lobf) using numpy's polyfit function
lobf1 = np.polyfit(x, y, 1)  # first degree polynomial
lobf2 = np.polyfit(x, y, 2)  # second degree polynomial
lobf3 = np.polyfit(x, y, 3)  # third degree polynomial

# you can now use the lines of best fit to calculate the 
# value anywhere within the domain using numpy's polyval function
# FIRST, create a figure and a plotting axis within the fig
fig = pl.figure(figsize=(3.25, 2.5))
ax0 = fig.add_subplot(111)

# now use polyval to calculate your y-values at every x
x = np.arange(0, 20, 0.1)
ax0.plot(x, np.polyval(lobf1, x), 'k')
ax0.plot(x, np.polyval(lobf2, x), 'b')
ax0.plot(x, np.polyval(lobf3, x), 'r')

# add a legend for niceness
ax0.legend(('Degree 1', 'Degree 2', 'Degree 3'), fontsize=8, loc=2)

# you can label the axes whatever you like
ax0.set_ylabel('My y-label', fontsize=8)
ax0.set_xlabel('My x-label', fontsize=8)

# you can show the figure on your screen
fig.show()

# and you can save the figure to your computer in different formats
# specifying bbox_inches='tight' helps eliminate unnecessary whitespace around
# the axis when saving...it just looks better this way.
pl.savefig('figName.png', dpi=500, bbox_inches='tight')
pl.savefig('figName.pdf', bbox_inches='tight')

# don't forget to close the figure
pl.close('all')