简体   繁体   English

如果稍后再添加print(),Python将为我提供不同的输出

[英]Python gives me different outputs if I add a print() later on

I'm super new to programming and just wanted to make something to find the approximate value of x for the equation x^3 - 1 = x . 我对编程非常陌生,只想做一些事情来找到方程x^3 - 1 = xx的近似值。 I know that -2 is greater than 0 and -1 is less. 我知道-2大于0-1小于。 My thought is that if I find the average and check if it's greater or less than 0 , I can redefine a and b and repeat until I get an approximate value. 我的想法是,如果我找到平均值并检查它是否大于或小于0 ,则可以重新定义ab并重复直到得到一个近似值。 I've been having a hard time getting it to act right though. 不过,我一直很难使它正确执行。 For example if I run this block without the print(i), I'll get -1.5 which would be the average, but when I put a print(total) within the function equation(n) to see if it's working right, it doesn't even show me that and just outputs -8.881784197001252e-16 . 例如,如果我在没有print(i)的情况下运行此块,我将得到-1.5 ,这是平均值,但是当我将print(total)放到函数equation(n)以查看其是否正常工作时,它会甚至没有告诉我,仅输出-8.881784197001252e-16 If I put print(i) at the end of the if/else possibilities, such as this, it prints 16 and then -8.881784197001252e-16 . 如果我将print(i)放在if/else可能性的末尾,例如这样,它将打印16 ,然后-8.881784197001252e-16 I'm using PyCharm CE. 我正在使用PyCharm CE。

Beyond this glitch, is my logic correct? 除了这个小故障,我的逻辑是否正确? By setting the placeholder to 1 it will run the while loop. 通过将占位符设置为1 ,它将运行while循环。 The while loop will get a new value of n and run the function, compare it to 0 , then reassign a or b depending on that comparison? while循环将获取新的n值并运行该函数,将其与0进行比较,然后根据该比较重新分配ab Thanks in advance. 提前致谢。

a = float(-2)
b = float(-1)
n = ((a+b)/2)
print(n)

def equation(n):

    total = float((n - n**3 - 1))

    return total

i = 1

while i != 0:
    n = ((a + b) / 2)
    if (equation(n)) > 0.0:
        a = n
        i = equation(n)
        print(i)

    else:
        b = n
        i = equation(n)
        print(i)

Moving all of the equation x^3 - 1 = x to one side should give x^3 - 1 - x = 0 or x - x^3 + 1 = 0 . 将所有方程x^3 - 1 = x移到一侧应使x^3 - 1 - x = 0x - x^3 + 1 = 0 You have a different equation in your function. 您的函数中有其他方程式。

Another problem is that there is no intersection between the two equations between x=-2 and x=-1 (see here ). 另一个问题是x=-2x=-1之间的两个方程之间没有交集(请参阅此处 )。 You'll need to expand your window to x=2 before you'll see an intersection. 您需要先将窗口扩展到x=2然后才能看到交集。

Something that often happens in numerical analysis (where you'll see this type of problem) is that rather than trying to find x that actually makes the equation give 0 , we look for a value of x that produces below an acceptable level of error. 一些经常发生的数值分析(在那里你会看到这种类型的问题)是不是试图找到x ,实际上使方程给出0 ,我们寻找的值x产生以下错误的可接受的水平。 Another approach is to test for while b - a > tol: 另一种方法是测试while b - a > tol:

If we use all of this to tweak what you've got, you'll have 如果我们使用所有这些来调整您所拥有的,您将拥有

a = float(-2)
b = float(2)
tol = 0.001

def equation(n):
    return float(n - n**3 + 1)

n = (a + b) / 2
iter = 0
while abs(equation(n) - 0) > tol and iter < 100:
    iter+=1

    if equation(n) > 0.0:
        a = n
    else:
        b = n

    n = (a + b) / 2

    print(iter,a,b,equation(n))

Note: this works fine if you remove the floats and just do 注意:如果您移除浮子,然后这样做,就可以正常工作

a = -2
b = 2
#...etc

because python already recasts values as necessary. 因为python已经根据需要重铸了值。 Try 尝试

>>> type(3)
<class 'int'>
>>> type(3.5)
<class 'float'>
>>> type(float(3))
<class 'float'>
>>> type(3/5)
<class 'float'>

so python will store the result as a float as soon as it is necessary. 因此python将在必要时立即将结果存储为浮点数。

The immediate problem is the limited precision of floats. 当前的问题是浮子精度有限。 If you print a and b after a hundred iterations, you get: 如果在一百次迭代后打印ab ,则会得到:

a, b = -1.324717957244746, -1.3247179572447458
print((a + b) / 2  # -1.3247179572447458, the same as b

So at some point, b never changes, which is why you get an infinite loop. 因此,在某些时候,b永远不会改变,这就是为什么会出现无限循环的原因。 If we evaluate equation at the average of a and b , you'll get -8.881784197001252e-16, the value you were always seeing. 如果我们以ab的平均值评估equation ,您将得到-8.881784197001252e-16,这是您一直看到的值。

But this will never converge to exactly zero because the solution is irrational , so even if you had infinite precision, equation would never equal zero. 但是,这绝不会收敛到恰好为零,因为该解决方案是不合理的 ,所以即使你有无限的精度,方程永远不会等于零。

The common way to resolve this issue is to avoid comparing floats: 解决此问题的常用方法是避免比较浮点数:

if a == b               # don't do this
if abs(a - b) < epsilon      # do this, where epsilon is some small value

(Note: what you're describing is the bisection method , which is slower than higher order algorithms eg Newton's method, which you can use since you can get the derivative) (注意:您要描述的是二分法 ,它比高阶算法(例如牛顿法)要慢,您可以使用它,因为可以获得导数)

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

相关问题 返回并打印在 Python 中给出不同的输出 - Return and print giving different outputs in Python 使用 python 请求 API 给我在 Raspberry Pi 上的错误输出 - Requesting to an API with python gives me incorrect outputs on Raspberry Pi 相同的python代码块在不同的时间给出不同的输出 - Same python code block gives different outputs at different time 如何在 python 中打印完整的相关输出数组? 另外,如果你能告诉我如何解释它们,那就太好了/ - How do I print the full array of correlation outputs in python? Also, if you could inform me how to interpret them, that would be wonderful/ 打印到 Python 3 中的混合输出? - Print to mixed outputs in Python 3? 为什么 python 2 和 3 对于某些十六进制值有不同的打印输出? - Why python 2 and 3 have different print outputs for some hex values? 打印和file.write提供不同的输出,Python - Print and file.write giving different outputs, Python 获取一个打印语句两次打印一个值的不同输出,python - Getting a print statement printed twice with different outputs for one value, python 尝试打印函数时,Python给我“ None” - Python gives me “None” when trying to print a function Pyhook由于某种原因给了我奇怪的输出 - Pyhook gives me weird outputs for some reason
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM