[英]How to make python output more decimal places of a recurring decimal?
```python
import decimal
x=[]
#functions etc. x is changed
#now returns is a list full of integers
print(sum(x)/len(x))
#This happens to give 0.6999
print(decimal.Decimal(sum(x)/len(x))
# This happens to give 0.6998999999996034 blah blah blah
```
The decimal module gives too many decimal places and round(decimal.Decimal(x),5) gives 0.69990 小数模块给出的小数位数太多,而round(decimal.Decimal(x),5)给出0.69990
I would like it to output 0.69999(5 dp) but it outputs 0.6999 or 0.69990 我希望它输出0.69999(5 dp),但输出0.6999或0.69990
You can try something like this 您可以尝试这样的事情
x=0.6999932
g = float("{0:.5f}".format(x))
print(g)
#output be like
0.69999
you already have the right answer: round(decimal.Decimal(x),5)
which gives 0.69990
. 您已经有了正确的答案:
round(decimal.Decimal(x),5)
得到0.69990
。 In your case, you should not expect 0.69999
, it is not even close to 0.699899999999
. 就您而言,您不应期望
0.69999
,甚至不接近0.699899999999
。 The python built-in function round
is good to use, but sometimes it can be surprising, see more details here python内置函数
round
很好用,但有时可能令人惊讶,请在此处查看更多详细信息
To summary: 总结一下:
import decimal
x=0.699899999
print("x =", x)
g = round(decimal.Decimal(x),5)
print("rounded:", g)
output: 输出:
x = 0.699899999
rounded: 0.69990
The number 0.699899999999...
is mathematically equivalent to 0.6999000...
, assuming the 9
s repeat farther than we want to go before we round things off. 数字
0.699899999999...
在数学上等价于0.6999000...
,假设9
s的重复距离比四舍五入前的0.6999000...
远。
This is the same as the question of why 0.9999...
is equal to 1
(for which you can find many explanations online, I'm fond of this one myself), just shifted several decimal places to the right. 这与为什么
0.9999...
等于1
的问题相同(为此您可以在网上找到很多解释,我自己很喜欢这个解释),只是向右移了几个小数位。 All the 9
s at the end turn into a 1
. 最后的所有
9
变成1
。 That one gets added to the last 8
and turn it into a 9
. 那个加到最后
8
,然后变成9
。 That's all followed by infinite zeros, which Python omits by default. 这之后是无限零,Python默认会忽略该零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.