簡體   English   中英

如何使python輸出一個重復小數點的更多小數位?

[英]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
```

小數模塊給出的小數位數太多,而round(decimal.Decimal(x),5)給出0.69990

我希望它輸出0.69999(5 dp),但輸出0.6999或0.69990

您可以嘗試這樣的事情

x=0.6999932
g = float("{0:.5f}".format(x))
print(g)

#output be like
0.69999

您已經有了正確的答案: round(decimal.Decimal(x),5)得到0.69990 就您而言,您不應期望0.69999 ,甚至不接近0.699899999999 python內置函數round很好用,但有時可能令人驚訝,請在此處查看更多詳細信息

總結一下:

import decimal
x=0.699899999
print("x =", x)
g = round(decimal.Decimal(x),5)
print("rounded:", g)

輸出:

x = 0.699899999
rounded: 0.69990

數字0.699899999999...在數學上等價於0.6999000... ,假設9 s的重復距離比四舍五入前的0.6999000...遠。

這與為什么0.9999...等於1的問題相同(為此您可以在網上找到很多解釋,我自己很喜歡這個解釋),只是向右移了幾個小數位。 最后的所有9變成1 那個加到最后8 ,然后變成9 這之后是無限零,Python默認會忽略該零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM