如何绘制变量 n 和 errorp 的图表?

huangapple go评论78阅读模式
英文:

How can I plot a graph for the variables n and errorp?

问题

以下是代码的翻译部分:

import math
x = float(input())
term = 1
sum = 1
n = 1
eps = 10**-7
while abs(term/sum) > eps:
    term = -x/n * term
    sum = sum + term
    n = n + 1.
print(n)
print(sum)
error = 100 - (sum * 100 / math.exp(-x))
print(abs(error), "%")

请注意,这只是代码的翻译,没有其他内容。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:
import math
x= float(input())
term = 1
sum = 1
n = 1
eps = 10**-7
while abs(term/sum) > eps:
    term = -x/n * term
    sum  = sum + term
    n = n + 1.
print (n)
print (sum)
error = 100 - (sum * 100 /math.exp(-x))
print(abs(error), "%")

The above code calculates the value of e^-x to a certain accuracy and compares it to the value of the built-in function. I'm trying to plot a graph between n (The number of iterations needed to reach the desired accuracy) and errorp (The error in the value after every iteration). I have imported matplotlib and tried using a list but didn't work. It doesn't let me append any values, and each list I make contains only the final value rather than the values of errorp after every iteration. So, the graph doesn't even show.

How can I plot the relation between them?

Thanks in advance.

答案1

得分: 1

你应该将错误值存储在一个列表中。在循环的每一步中附加计算出的错误。然后绘制迭代和错误列表相互对比:

import matplotlib.pyplot as plt
import math

x = float(input("输入 x 值:"))
term = 1
s = 1
n = 1
eps = 10**-7
error_lst = []

while abs(term/s) > eps:
    term = -x/n * term
    s = s + term
    error_lst.append(abs(100 - (s * 100 / math.exp(-x)))
    n = n + 1

fig, ax = plt.subplots()
ax.plot(range(1, int(n)), error_lst)
ax.set_title(f"{x} (exp({-x}) 的近似迭代")
ax.set_xlabel('迭代次数')
ax.set_ylabel('误差百分比')
plt.show()

输出:

如何绘制变量 n 和 errorp 的图表?

英文:

You should store the error values in a list. Append the computed error at each step of the loop. Then plot the iteration and error lists against eachother:

import matplotlib.pyplot as plt
import math

x=float(input("Enter x value: "))
term = 1
s = 1
n = 1
eps = 10**-7
error_lst = []
while abs(term/s) > eps:
    term = -x/n * term
    s  = s + term
    error_lst.append(abs(100 - (s * 100 /math.exp(-x))))
    n = n + 1.

fig, ax = plt.subplots()
ax.plot(range(1, int(n)), error_lst)
ax.set_title(f"Iterations for x={x} (approx. of exp({-x}))")
ax.set_xlabel('iterations')
ax.set_ylabel('error in %')
plt.show()

Output:

如何绘制变量 n 和 errorp 的图表?

huangapple
  • 本文由 发表于 2023年3月4日 02:18:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定