【问题标题】:While Loop (Python 3.7.4)While 循环 (Python 3.7.4)
【发布时间】:2019-09-25 02:43:38
【问题描述】:

我是一名刚接触 Python 编程的学生,我在理解如何让 Python 使用这个 While 循环来处理给我的方程式时遇到了问题。

问题说明:

a^x 可以使用以下系列进行评估: a^x = 1 + x*ln(a) + ((x*ln(a))^2/2! + ((x*ln(a))^3/3! + ... + ((x*ln(a))^n/n!

a = 1.52

x = 3.14

继续您的系列,直到绝对项小于 10^-6 或您已计算出 100 个项。

输出你的a^x系列,使用的词条数(n)

我在 Python 3.7.4 上的尝试:

from math import *

outFile = open("HW3out.txt", "a")
print("Problem 4 soln",file = outFile)

maxt = 100
tol = 1e-6
x = 3.14
a = 1.52
z = (x*log*a)

term = z
n = 1
sum = z

while abs(term) < tol and n < maxt:
   n = n+1
   term = (x*log*a)**n/n
   sum = sum + term

a**x = sum
diff = a**x - a

print("a^x", a**x, " Correct Value ", a, file = outFile)
print("x ", x, "n ", n, "term ", term, "diff ", diff, file = outFile)

outFile.close()`

我知道我的代码有问题,但我不明白是什么。我使用了我教授的例子,他在课堂上做了一个不同的方程,但我仍然不知道我做错了什么。

【问题讨论】:

  • 你怎么知道你做错了什么?您收到错误消息了吗?
  • 显而易见的问题:log 是一个函数,而不是某种常量。 x * log * a 是荒谬的,因为将数字乘以函数是荒谬的。我怀疑你想要x * log(a),它在a 上调用log,并返回一个可以乘以x 的新数字。
  • 另外a**x是一个表达式,你不能给它赋值
  • 给出你得到的错误
  • 看来你需要:z = x * log(a),当你在while循环中更新term时你需要:term = term * z / n

标签: python while-loop


【解决方案1】:

回过头来看反馈,发现问题之一是我的

a**x = sum

我删除了,其他人建议我使用 term = term*z**n/n 而不是 term = (x*log*a)**n/n 这是我的新文件现在的样子:

from math import *

outFile = open("HW3out.txt", "a")
print("Problem 4 soln",file = outFile)

maxt = 100
tol = 1e-6
x = 3.14
a = 1.52
z = (x*log(a))

term = z
n = 1
sum = z

while abs(term) < tol and n < maxt:
   n = n+1
   term = term*z**n/n
   sum = sum + term


diff = a**x - a

print("a^x", a**x, " Correct Value ", a, file = outFile)
print("x ", x, "n ", n, "term ", term, "diff ", diff, file = outFile)


outFile.close()

我来自我的outFile

Problem 4 soln
a^x 3.7238215950300577  Correct Value  1.52
x  3.14 n  1 term  1.314750451454701 diff  2.2038215950300577

我认为这是正确的,因为程序现在终于可以正常运行了

【讨论】:

  • 我建议 term = term * z / n(不是 term = term * zn/n)。你的最终错误有多小,即 abs(ax - [while 循环中总和的最终值])?
猜你喜欢
  • 2014-11-02
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2014-05-30
相关资源
最近更新 更多