四舍五入到任意数量的有效数字 [英] Rounding to an arbitrary number of significant digits

查看:32
本文介绍了四舍五入到任意数量的有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将任何数字(不仅仅是整数 > 0)四舍五入为 N 个有效数字?

How can you round any number (not just integers > 0) to N significant digits?

例如,如果我想四舍五入为三位有效数字,我正在寻找一个可以采用的公式:

For example, if I want to round to three significant digits, I'm looking for a formula that could take:

1,239,451 并返回 1,240,000

1,239,451 and return 1,240,000

12.1257 并返回 12.1

12.1257 and return 12.1

.0681 并返回 .0681

.0681 and return .0681

5 并返回 5

当然,算法不应被硬编码为仅处理 3 中的 N,尽管这只是一个开始.

Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.

推荐答案

这是 Java 中的相同代码,没有其他答案所具有的 12.100000000000001 错误

Here's the same code in Java without the 12.100000000000001 bug other answers have

我也去掉了重复的代码,把power改成整数类型,防止n - d完成后出现浮动问题,让长中间的更清晰

I also removed repeated code, changed power to a type integer to prevent floating issues when n - d is done, and made the long intermediate more clear

该错误是由大数乘以小数引起的.相反,我将两个大小相似的数字相除.

The bug was caused by multiplying a large number with a small number. Instead I divide two numbers of similar size.

编辑
修复了更多错误.添加了对 0 的检查,因为它会导致 NaN.使函数实际使用负数(原始代码不处理负数,因为负数的对数是复数)

EDIT
Fixed more bugs. Added check for 0 as it would result in NaN. Made the function actually work with negative numbers (The original code doesn't handle negative numbers because a log of a negative number is a complex number)

public static double roundToSignificantFigures(double num, int n) {
    if(num == 0) {
        return 0;
    }

    final double d = Math.ceil(Math.log10(num < 0 ? -num: num));
    final int power = n - (int) d;

    final double magnitude = Math.pow(10, power);
    final long shifted = Math.round(num*magnitude);
    return shifted/magnitude;
}

这篇关于四舍五入到任意数量的有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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