四舍五入到 n 个有效数字 [英] Rounding to n significant digits

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

问题描述

我正在尝试在 MATLAB 中编写代码,将数字四舍五入为某些(如我所问)有效数字.

I'm trying to write code in MATLAB that will round number to certain (as I ask) significant digits.

我不知道该怎么做.有什么建议吗?

I'm not sure how to do it. Any suggestions?

推荐答案

四舍五入到 d 有效数字:

>> d = 3; %// number of digits
>> x = 5.237234; %// example number

>> D = 10^(d-ceil(log10(x)));
>> y = round(x*D)/D
y =
    5.2400

四舍五入到d 十进制数字:

>> d = 3; %// number of digits
>> x = 5.237234; %// example number

>> D = 10^d;
>> y = round(x*D)/D
y =
    5.2370

编辑

实际上更简单:round 函数支持以下选项:

Actually it's easier: the round function supports these options:

>> d = 3;
>> x = 5.237234;
>> y = round(x, d, 'significant')
y =
    5.2400

>> d = 3;
>> x = 5.237234;
>> y = round(x, d) %// or y = round(x, d, 'decimals')
y =
    5.2370

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

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