如何在Python中从0开始计算第n个浮点数 [英] How to compute the n-th floating point from 0 in python

查看:208
本文介绍了如何在Python中从0开始计算第n个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道浮点不均匀分布。我想从 Python 中从0开始计算第n个浮点数。有没有一种有效的方法来做到这一点?



让nth_fp成为函数。它需要一个整数并输出一个浮点数。以下属性是必要的:

  1。 nth_fp(0)应该是0 

2.如果n> 0

,则nth_fp(n)> 0如果n <0 $,则nth_fp(n)<0 b
$ b 4.nth_fp(m)> nth_fp(n)if m> n


解决方案

那些制定了 IEEE 64位双打非常聪明。他们确保下一个更高的可表示浮点值是从前一个浮点值开始的一个简单的整数增量, 0.0 是一个全零的位模式。因此,对于一个正数 n ,您可以直接将位模式直接转换为浮点数。

  import struct 

def nth_fp(n):
if n < 0:
sign_bit = 0x8000000000000000
n = -n
else:
sign_bit = 0
if n> = 0x7ff0000000000000:
raise ValueError('out ($'$')
bit_pattern =



正如您所看到的,负数只需要在总体模式中添加一个位。


We know floating points are not distributed evenly. I want to calculate the n-th floating point from 0 in Python. Is there an efficient way to do that?

Let nth_fp be the function. It takes an integer and outputs a floating-point number. The following properties are necessary:

1. nth_fp(0) should be 0

2. nth_fp(n)>0 if n>0 

3. nth_fp(n)<0 if n<0

4.nth_fp(m)>nth_fp(n) if m>n

解决方案

The people who laid out the format of IEEE 64-bit doubles were very clever. They ensured that the next higher representable floating point value is a simple integer increment up from the previous one, with 0.0 being a bit pattern of all zeros. Thus for a positive number n you can simply convert the bit pattern to floating point directly.

import struct

def nth_fp(n):
    if n < 0:
        sign_bit = 0x8000000000000000
        n = -n
    else:
        sign_bit = 0
    if n >= 0x7ff0000000000000:
        raise ValueError('out of range')
    bit_pattern = struct.pack('Q', n | sign_bit)
    return struct.unpack('d', bit_pattern)[0]

As you can see, negative numbers only require the addition of a single bit to the overall pattern.

这篇关于如何在Python中从0开始计算第n个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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