加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python – 如何将浮点数舍入为1位有效数字

发布时间:2020-12-20 13:14:38 所属栏目:Python 来源:网络整理
导读:我想将浮点数向下舍入到特定数量的有效数字.非常类似于这个答案: https://stackoverflow.com/a/3411435/281021但不是正常的round()行为,它应该总是向下舍入.我不能使用math.floor()因为它将float转换为int. 基本上,0.45应该变为0.4而不是0.5. 并且1945.01应
我想将浮点数向下舍入到特定数量的有效数字.非常类似于这个答案: https://stackoverflow.com/a/3411435/281021但不是正常的round()行为,它应该总是向下舍入.我不能使用math.floor()因为它将float转换为int.

基本上,0.45应该变为0.4而不是0.5.
并且1945.01应该变为1000.0而不是2000.0.

解决方法

科学表征似乎是要走的路,但数字技术通常比字符串技术更快.你确实得到偶然的浮点错误…

from math import *


def roundDown(x,sigfigs=1): #towards -inf 
    exponent = floor(log10(copysign(x,1))) #we don't want to accidentally try and get an imaginary log (it won't work anyway)
    mantissa = x/10**exponent #get full precision mantissa
    # change floor here to ceil or round to round up or to zero
    mantissa = floor(mantissa * 10**(sigfigs-1)) / 10**(sigfigs-1) #round mantissa to sigfigs
    return mantissa * 10**exponent

向零或inf舍入就像将地板改为ceil或round一样容易.以数字方式计算尾数和指数而不是转换为字符串的另一个好处是可以轻松更改sigfigs的数量

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读