Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

matlab - About floating point precision: why the iteration numbers are not equal?

There are two similar matlab programs, one iterates 10 times while another iterates 11 times.

One:

i = 0;
x = 0.0;
h = 0.1;
while x < 1.0
    i = i + 1;
    x = i * h;
    disp([i,x]);
end

Another:

i = 0;
x = 0.0;
h = 0.1;
while x < 1.0
    i = i + 1;
    x = x + h;
    disp([i,x]);
end

I don't understand why there is difference between the floating point add operation and the multiple.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be very carefully when you do iterations with float counters. Just as an example I'll show you what happens in your case (it is a Java program but your case should be the same): click here to run it yourself

double h = 0.1;
System.out.println(10*h-1.0);
System.out.println(h+h+h+h+h+h+h+h+h+h-1.0);

It just prints the difference to one when doing a multiplication vs. seprarate additions.

Since the representation of floats is not exact the result looks like this:

0.0
-1.1102230246251565E-16

Thus if you use this as a looping condition in the latter case there will be an additional iteration (one is not yet reached).

Try to use the counter variable i which is an integer and you won't run into such issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...