程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了基于python中所需精度的unround float大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决基于python中所需精度的unround float?

开发过程中遇到基于python中所需精度的unround float的问题如何解决?下面主要结合日常开发的经验,给出你关于基于python中所需精度的unround float的解决方法建议,希望对你解决基于python中所需精度的unround float有所启发或帮助;

python 中,是否有方法/库可以根据所需的精度将数字展开/展开为一系列数字?

这是一个例子。

给定我们有一个数字:5.86,十进制精度/小数位数:2 位,我们解开/解开数字:

  • 精确到3范围是[5.855; 5.864](差异:9)
  • 精确到4范围是[5.8550; 5.8649](差异:99)

附言下面提供了自己的答案

解决方法

当我在写这个问题时 - 我已经设法使用一些定制的函数来解决它。也许它会对某人有用。

解决方案

def split_value_into_range(number,needed_precision,current_precision = -1):
    # you can decide if you want to pass the current precision from outside or not..
    # probably doesn't really matter perfoRMANce wise
    if current_precision == -1:
        # convert to String and remove Trailing zeros from float
        numberStr = f'{number:g}'

        # get current precision
        scale = numberStr[::-1].find('.')
        current_precision = scale

    # get precision difference
    precision_diff = needed_precision - current_precision

    if precision_diff < 1:
        raise Exception("Operation not supported. NOTE: modify the function to suit your needs")

    # get number of 'digits' to substract and to add
    partial_substractor = 5 * (10 ** (precision_diff - 1))
    partial_adder = partial_substractor - 1

    # count how many `digits` are in range
    diff = partial_substractor + partial_adder

    denominator = 10 ** needed_precision
    substractor = partial_substractor / denominator
    adder = partial_adder / denominator

    min_range = round(number - substractor,needed_precision)
    max_range = round(number + adder,needed_precision)

    return min_range,max_range,diff

number = 5.86

min,max,diff = split_value_into_range(number,3,2)
print(f"min={min},max={max},diff={diff}")

min,4)
print(f"min={min},5)
print(f"min={min},6)
print(f"min={min},diff={diff}")

输出

@H_660_3@min=5.855,max=5.864,diff=9
min=5.855,max=5.8649,diff=99
min=5.855,max=5.86499,diff=999
min=5.855,max=5.864999,diff=9999

已知限制

如果您想将尾随零保留在浮点数中,那么您必须使用 decimal。不要使用float。 :) 在上面的示例中,实际上没有必要对 @H_660_3@min_range 进行舍入,因为无论如何,python 都会处理尾随零。不过,我希望代码在输出结果中保持一致,因此我将其保留在代码中。 . 另外,据我所知,当您从 floats 中添加或减去值时,可能会有一些最小偏差,这是由于系统在 CPU 指令级别(低级内容)中的浮点处理......所以请记住这一点使用浮点数时 :)

附言如果您正在阅读此答案并知道如何解决问题的另一种方法 - 请尽可能附上性能比较报告:)

大佬总结

以上是大佬教程为你收集整理的基于python中所需精度的unround float全部内容,希望文章能够帮你解决基于python中所需精度的unround float所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:float