python設定資料精度 Python設定小數精度

2021-10-11 12:31:15 字數 1697 閱讀 4785

我正在編寫乙個用算術編碼進行編碼的小**.我需要設定乙個確定的精度,但我必須做錯事.這是**:

def encode(string, probabilities):

getcontext().prec = 28

start = 0.0

width = 1.0

for ch in string:

d_start, d_width = probabilities[ch]

start += d_start*width

width *= d_width

return random.uniform(start, start + width)

正如我在python文件中讀到的getcontext().prec應該設定我願意使用的精度.在一些迭代之後,d_start和d_with非常小(~e ^ -20)並且變數start和width從那一刻起保持相同的valor.

如果需要進一步的資訊,請不要猶豫要求.

提前致謝

在這裡你有結果:

0.00.16

0.224

0.224

0.22784

0.22784

0.2280448

0.22812672

0.22812672

0.2281316352

0.2281316352

0.228131897344

0.228132002202

0.228132002202

0.228132008493

0.228132008493

0.228132008829

0.228132008963

0.228132008963

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

0.228132008971

解決方法:

問題是getcontext().prec僅用於decimal.decimal變數…並且您將start和width定義為float.

你應該強制使用decimal,例如那種方式(假設從十進位制導入*)

def encode(string, probabilities):

getcontext().prec = 28

start = decimal('0.0')

width = decimal('1.0')

for ch in string:

d_start, d_width = probabilities[ch]

start += decimal(d_start)*width

width *= decimal(d_width)

return random.uniform(float(start), float(start + width))

標籤:python,python-3-x

UltraEdit設定語法高亮支援python

ultraedit預設不支援python的語法高亮,通過以下設定可實現語法高亮 1.在 下有各種語言的語法高亮支援,找到對應的python版本,現在已有的為python2.5和2.6,開啟鏈結,將頁面內容儲存為.uew格式,我使用的是python2.6,儲存為python2.6.uew 3.需要注意...

MATLAB 設定 資料游標的精度

1 新建乙個名稱為newcallback.m的m檔案,如下 function output txt myfunction obj,event obj display the position of the data cursor obj currently not used empty event ...

C 中輸出資料精度設定問題

該精度設定後儲存為n位有效數字的資料,包括小數點前的資料。若只想保留小數點後的精度,則可以在cou流 中加入fixed標識,即設定浮點數以固定的小數字顯示 cout.precision 2 cout還可以呼叫setiosflags ios fixed 來設定只保留小數點後n位有效數值 cout.pr...