简单的Perl For循环 [英] Simple Perl For-Loop
问题描述
我有一个for循环,我想每次增加0.1的变量,但是这个值的变化与增量不同,我不确定为什么。
我已经简化了for循环,它仍然给出了一个奇怪的输出:
$ p $ for(my $ t = 1000; $ t < 1500; $ t + = 0.1){
print$ t \\\
;
$ b $ p
1034.9
1035
1035.1
1035.2
1035.3
1035.4
1035.49999999999
1035.59999999999
1035.69999999999
1035.79999999999
1035.89999999999
1035.99999999999
1036.09999999999
1036.19999999999
1036.29999999999
[然后就这样到1500]
我不知道小数点在哪里。这是一个问题,我对Perl的理解?
提前致谢。
$ perl -e'printf%.20g\\\
, 0.1'
0.10000000000000001
不要将浮点数与另一个浮点数进行比较,注意错误的累积。
这里简单的解决方法是使用整数进行算术运算,并在需要时生成浮点数字 简化为
pre $ for(my $ tx10 = 10000; $ tx10 <15000; ++ $ tx10){
my $ t = $ tx10 / 10;
打印$ t \\\
;
为我的$ tx10(10000..14999){
my $ t = $ tx10 / 10;
打印$ t \\\
;
$ / code>
____ ____ ____
0.1 = 0.00011 0.4 = 0.0110 0.7 = 0.10110
____ ____
0.2 = 0.0011 0.5 = 0.1 0.8 = 0.11001
____ ____ ____
0.3 = 0.01001 0.6 = 0.1001 0.9 = 0.11100
I have a for loop and I want to increment the variable by 0.1 each time, however the value changes differently from the increment and I am unsure as to why.
I've simplified the for loop and it still gives a strange output:
for (my $t = 1000; $t < 1500 ;$t+=0.1) {
print "$t\n";
}
It prints:
1034.9
1035
1035.1
1035.2
1035.3
1035.4
1035.49999999999
1035.59999999999
1035.69999999999
1035.79999999999
1035.89999999999
1035.99999999999
1036.09999999999
1036.19999999999
1036.29999999999
[it then goes on like this to 1500]
I do not know where the decimal places are coming from. Is this a problem with my understanding of Perl?
Thanks in advance.
1/10 is a periodic number in binary like 1/3 is in decimal. It cannot be represented exactly as a floating point number.
$ perl -e'printf "%.20g\n", 0.1'
0.10000000000000001
Never compare a floating pointer number to another without involving a tolerance, and be wary of accumulation of error.
The simple solution here to to do the arithmetic using integers, and generate the floating point numbers when needed
for (my $tx10 = 10000; $tx10 < 15000; ++$tx10) {
my $t = $tx10/10;
print "$t\n";
}
which simplifies to
for my $tx10 (10000..14999) {
my $t = $tx10/10;
print "$t\n";
}
____ ____ ____
0.1 = 0.00011 0.4 = 0.0110 0.7 = 0.10110
____ ____
0.2 = 0.0011 0.5 = 0.1 0.8 = 0.11001
____ ____ ____
0.3 = 0.01001 0.6 = 0.1001 0.9 = 0.11100
这篇关于简单的Perl For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!