两个花车之间的花车数量 [英] Number of floats between two floats

查看:165
本文介绍了两个花车之间的花车数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个Python浮点数 a b ,有没有简单的方法来找出有多少可表示的真正的数字是在IEEE-754表示(或者是机器使用的任何表示)之间的两个数字之间的数字吗?

解决方案

知道你将使用什么 - 但是,如果两个浮点数有相同的指数,它应该是可能的。由于指数保持在高位,因此将float字节(本例中为8个字节)作为整数加载并从另一个中减去一个,应该给出所需的数字。我使用struct模型将浮点数打包成二进制表示,然后将这些浮点数解包为(C,8字节)long int:

 >>> import struct 
>>> a = struct.pack(dd,1.000000,1.000001)
>>> b = struct.unpack(ll,a)
>>> b [1] - b [0]
4503599627
>>> a = struct.pack(dd,1.000000000,1.000000001)
>>> b = struct.unpack(ll,a)
>>> b [1] - b [0]
4503600
>>>


Say I have two Python floats a and b, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representation (or whatever representation the machine used is using)?

解决方案

I don'tknow what you will be using this for - but, if both floats have the same exponent, it should be possible. As the exponent is kept on the high order bits, loading the float bytes (8 bytes in this case) as an integer and subtracting one from another should give the number you want. I use the struct model to pack the floats to a binary representation, and then unpack those as (C, 8 byte) long ints:

>>> import struct
>>> a = struct.pack("dd", 1.000000,1.000001)
>>> b = struct.unpack("ll",a)
>>> b[1] - b[0]
4503599627
>>> a = struct.pack("dd", 1.000000000,1.000000001)
>>> b = struct.unpack("ll",a)
>>> b[1] - b[0]
4503600
>>>

这篇关于两个花车之间的花车数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆