你如何在Perl中使用浮点数? [英] How do you round a floating point number in Perl?
问题描述
如何将十进制数(浮点数)舍入到最近的整数?
例如
1.2 = 1
1.7 = 2
perldoc -q round
$ b
Perl有一个round()函数?那么ceil()和floor()呢?
Trig函数?
记住int()
只能截断为0
。为了四舍五入到一定数量的数字,sprintf()
或printf()
通常是最简单的
路线。
printf(%。3f,3.1415926535); #打印3.142
ceil()
POSIX
/ code>,floor()
,以及许多其他数学和三角函数
函数。
使用POSIX;
$ ceil = ceil(3.5); #4
$ floor = floor(3.5); #3
在5.000到5.003 perls中,三角函数在Math :: Complex
模块。用5.004,Math :: Trig
模块(标准Perl
分布的一部分)实现了三角函数。在内部,
使用Math :: Complex
模块,一些函数可以从
实轴跳出到复平面,例如2的反正弦。
金融应用程序中的舍入可以具有严重的影响,并应使用
的舍入方法精确指定。在这些
的情况下,它可能不会相信Perl使用的任何系统舍入是
,而是实现舍入函数,您自己需要
。
要知道为什么,请注意在中间点
交替的情况下如何仍然存在问题:
<$ p ($ i = 0; $ i <1.01; $ i + = 0.05){printf%.1f,$ i}
0.0 0.1 0.1 $ p>0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
0.8 0.8 0.9 0.9 1.0 1.0
不要怪Perl。这和C一样.IEEE说我们必须做
这个。绝对值在2 ** 31
(在
32位机器上)下的整数的Perl数字的工作原理与数学整数非常类似。
其他号码不能保证。
How can I round a decimal number (floating point) to the nearest integer?
e.g.
1.2 = 1
1.7 = 2
Output of perldoc -q round
Does Perl have a round() function? What about ceil() and floor()? Trig functions?Remember that
int()
merely truncates toward0
. For rounding to a certain number of digits,sprintf()
orprintf()
is usually the easiest route.
printf("%.3f", 3.1415926535); # prints 3.142
The
POSIX
module (part of the standard Perl distribution) implementsceil()
,floor()
, and a number of other mathematical and trigonometric functions.
use POSIX; $ceil = ceil(3.5); # 4 $floor = floor(3.5); # 3
In 5.000 to 5.003 perls, trigonometry was done in the
Math::Complex
module. With 5.004, theMath::Trig
module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses theMath::Complex
module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2.Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.
To see why, notice how you'll still have an issue on half-way-point alternation:
for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0
Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under
2**31
(on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.
这篇关于你如何在Perl中使用浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!