久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Python和一般情況下的浮點相等

floating point equality in Python and in general(Python和一般情況下的浮點相等)
本文介紹了Python和一般情況下的浮點相等的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一段代碼的行為不同,具體取決于我是通過字典獲取轉換因子還是直接使用它們.

I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.

以下代碼將打印 1.0 == 1.0 ->錯誤

但如果您將 factors[units_from] 替換為 10.0 并將 factors[units_to ] 替換為 1.0/2.54它將打印 1.0 == 1.0 ->是的

But if you replace factors[units_from] with 10.0 and factors[units_to ] with 1.0 / 2.54 it will print 1.0 == 1.0 -> True

#!/usr/bin/env python

base = 'cm'
factors = {
    'cm'        : 1.0,
    'mm'        : 10.0,
    'm'         : 0.01,
    'km'        : 1.0e-5,
    'in'        : 1.0 / 2.54,
    'ft'        : 1.0 / 2.54 / 12.0,
    'yd'        : 1.0 / 2.54 / 12.0 / 3.0,
    'mile'      : 1.0 / 2.54 / 12.0 / 5280,
    'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}

# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'

base_value = val / factors[units_from]
ret = base_value * factors[units_to  ]
print ret, '==', 1.0, '->', ret == 1.0

首先讓我說我很確定這里發生了什么.我以前在 C 中見過它,只是在 Python 中從未見過,但自從 Python 在 C 中實現后,我們就看到了.

Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.

我知道浮點數會改變從 CPU 寄存器到緩存并返回的值.我知道,如果其中一個被分頁而另一個駐留在寄存器中,那么比較應該是兩個相等的變量將返回 false.

I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.

問題

  • 避免此類問題的最佳方法是什么?...在?? Python 中或一般情況下.
  • 我做錯了什么嗎?

旁注

這顯然是一個精簡示例的一部分,但我想要做的是提供長度、體積等類別,可以與同一類別但具有不同單位的其他對象進行比較.

This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.

反問句

  • 如果這是一個潛在的危險問題,因為它會使程序以不確定的方式運行,編譯器在檢測到您正在檢查浮點數的相等性時是否應該發出警告或錯誤
  • 編譯器是否應支持將所有浮點相等檢查替換為足夠接近"函數的選項?
  • 編譯器是否已經這樣做了,我只是找不到信息.

推薦答案

感謝您的回復.大多數都非常好,并提供了很好的鏈接,所以我只會這么說并回答我自己的問題.

Thanks for your responses. Most were very good and provided good links so I'll just say that and answer my own question.

Caspin 發布了這個 鏈接.

Caspin posted this link.

他還提到谷歌測試使用 ULP 比較,當我查看谷歌代碼時,我看到他們提到了與 cygnus-software 相同的確切鏈接.

He also mentioned that Google Tests used ULP comparison and when I looked at the google code I saw that they mentioned the same exact link to cygnus-software.

我最終用 C 語言實現了一些算法作為 Python 擴展,后來發現我也可以用純 Python 來實現.代碼貼在下面.

I wound up implementing some of the algorithms in C as a Python extension and then later found that I could do it in pure Python as well. The code is posted below.

最后,我可能只是將 ULP 差異添加到我的技巧包中.

In the end, I will probably just wind up adding ULP differences to my bag of tricks.

有趣的是,在兩個應該永遠不會離開內存的相等數字之間有多少浮點數.我讀過的一篇文章或谷歌代碼說 4 是一個不錯的數字……但在這里我可以達到 10.

It was interesting to see how many floating points are between what should be two equal numbers that never left memory. One of the articles or the google code I read said that 4 was a good number... but here I was able to hit 10.

>>> f1 = 25.4
>>> f2 = f1
>>> 
>>> for i in xrange(1, 11):
...     f2 /= 10.0          # to cm
...     f2 *= (1.0 / 2.54)  # to in
...     f2 *= 25.4          # back to mm
...     print 'after %2d loops there are %2d doubles between them' % (i, dulpdiff(f1, f2))
... 
after  1 loops there are  1 doubles between them
after  2 loops there are  2 doubles between them
after  3 loops there are  3 doubles between them
after  4 loops there are  4 doubles between them
after  5 loops there are  6 doubles between them
after  6 loops there are  7 doubles between them
after  7 loops there are  8 doubles between them
after  8 loops there are 10 doubles between them
after  9 loops there are 10 doubles between them
after 10 loops there are 10 doubles between them

<小時>

同樣有趣的是,當將其中一個作為字符串寫出并讀回時,相等數字之間有多少個浮點.


Also interesting is how many floating points there are between equal numbers when one of them is written out as a string and read back in.

>>> # 0 degrees Fahrenheit is -32 / 1.8 degrees Celsius
... f = -32 / 1.8
>>> s = str(f)
>>> s
'-17.7777777778'
>>> # floats between them...
... fulpdiff(f, float(s))
0
>>> # doubles between them...
... dulpdiff(f, float(s))
6255L

<小時>

import struct
from functools import partial

# (c) 2010 Eric L. Frederich
#
# Python implementation of algorithms detailed here...
# from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

def c_mem_cast(x, f=None, t=None):
    '''
    do a c-style memory cast

    In Python...

    x = 12.34
    y = c_mem_cast(x, 'd', 'l')

    ... should be equivilent to the following in c...

    double x = 12.34;
    long   y = *(long*)&x;
    '''
    return struct.unpack(t, struct.pack(f, x))[0]

dbl_to_lng = partial(c_mem_cast, f='d', t='l')
lng_to_dbl = partial(c_mem_cast, f='l', t='d')
flt_to_int = partial(c_mem_cast, f='f', t='i')
int_to_flt = partial(c_mem_cast, f='i', t='f')

def ulp_diff_maker(converter, negative_zero):
    '''
    Getting the ulp difference of floats and doubles is similar.
    Only difference if the offset and converter.
    '''
    def the_diff(a, b):

        # Make a integer lexicographically ordered as a twos-complement int
        ai = converter(a)
        if ai < 0:
            ai = negative_zero - ai

        # Make b integer lexicographically ordered as a twos-complement int
        bi = converter(b)
        if bi < 0:
            bi = negative_zero - bi

        return abs(ai - bi)

    return the_diff

# double ULP difference
dulpdiff = ulp_diff_maker(dbl_to_lng, 0x8000000000000000)
# float  ULP difference
fulpdiff = ulp_diff_maker(flt_to_int, 0x80000000        )

# default to double ULP difference
ulpdiff = dulpdiff
ulpdiff.__doc__ = '''
Get the number of doubles between two doubles.
'''

這篇關于Python和一般情況下的浮點相等的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Why I cannot make an insert to Python list?(為什么我不能插入 Python 列表?)
Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的開頭(最左端)插入一列)
Python psycopg2 not inserting into postgresql table(Python psycopg2 沒有插入到 postgresql 表中)
list extend() to index, inserting list elements not only to the end(list extend() 索引,不僅將列表元素插入到末尾)
How to add element in Python to the end of list using list.insert?(如何使用 list.insert 將 Python 中的元素添加到列表末尾?)
TypeError: #39;float#39; object is not subscriptable(TypeError:“浮動對象不可下標)
主站蜘蛛池模板: 中文字幕免费在线 | 欧美一级片a | 亚洲精品成人 | 国产丝袜一区二区三区免费视频 | 国产精品theporn | 亚洲国产精品一区二区第一页 | 亚洲一区综合 | 欧美一区二区三区视频 | 99久久婷婷国产综合精品首页 | 欧美精品91| 四虎影视一区二区 | 国产精品综合色区在线观看 | 国产精品久久久久久吹潮日韩动画 | 91人人视频在线观看 | 久久亚| 激情五月婷婷丁香 | av中文天堂 | 国产黑丝av| 午夜免费观看体验区 | 中文字幕一页二页 | 欧美黄在线观看 | 女女爱爱视频 | 日本黄色大片免费看 | 日本不卡在线观看 | 一级黄色毛片免费 | 婷婷开心激情综合五月天 | 台湾佬久久 | 亚洲精品成人av久久 | 天天干视频 | 久久久国产精品 | 欧美精品二区三区 | 日韩视频在线一区二区 | 网站一区二区三区 | 国产视频一区二区 | 91精产国品一二三区 | 亚洲精品黄色 | 国产一区2区 | 天天成人综合网 | 精品国产黄a∨片高清在线 www.一级片 国产欧美日韩综合精品一区二区 | 亚洲视频一区在线观看 | 日韩av一区二区在线观看 |