在python中从给定的double中获取第n个double数

2024-06-16 14:10:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题类似于another question,但我不知道如何用简单的方式扩展这个问题的答案。你知道吗

这里,我想从Python中给定的double计算第n个double。 该函数接受整数n,双精度x,并输出一个double,即x之后的n-th(如果n为负,则为之前的n-th)。有没有有效的方法?你知道吗

具体地说,设nth\u fp\u after为函数,则nth\u fp\u after(x,n)应等于nextafter(C)对x的应用的n倍;nth\u fp\u after(x,0)应为“x”,以此类推


Tags: 方法函数答案方式another精度整数double
1条回答
网友
1楼 · 发布于 2024-06-16 14:10:05

answer of the question you pointed to正是你问题的答案。这个答案解决了64位浮点的问题,这些浮点是python的C double等价物。你知道吗


好吧,如果你加上

struct.unpack('!i',struct.pack('!f',x))[0]

n并使用它调用另一个答案的函数,您应该得到它。你知道吗


通过修改的完整解决方案如下所示:

import struct

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

我为第二个参数添加了一个默认值,这样您就可以在两种情况下使用它,无论是否使用偏移量x。你知道吗

相关问题 更多 >