gpt4 book ai didi

python - python 中方程式的错误答案

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:51 25 4
gpt4 key购买 nike

试试 Wolphram Alpha - 这是正确的结果。

用 python 2.7.x 试试:

u = 4/3 * 6.67*1e-11*3.14*6378000*5515
print (u)

答案是 7.36691253546

这里哪里不对?

最佳答案

整数除法。 4/3 向下舍入时计算结果为 1。

使用 4.0 来强制浮点运算:

>>> 4.0/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998

或者使用 Python 3,其中浮点除法是默认的,或者使用 from __future__ import division 在 Python 2 中实现同样的效果:

Python 2.7.5 (default, May 22 2013, 12:00:45) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import division
>>> 4/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998

此行为记录在 Binary arithmetic operators section 下:

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception.

参见 PEP 238关于为什么在 Python 3 中改变了这种行为,以及对 from __future__ import division 语句的引用。

关于python - python 中方程式的错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com