Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 27
1.1.9.3 while
Loop
ОглавлениеA while
loop will be iterated as long as its predefined condition is satisfied and a break
statement is not encountered inside the loop.
1 (Ex. 7) A while Loop%nm119_7.m: example of while loop r=1; while r<10 r= input('\nType radius (or nonpositive number to stop):'); if r<=0, break, end %isempty(r)|r<=0, break, end v= 4/3*pi*r̂3; fprintf('The volume of a sphere with radius %3.1f =%8.2f\n',r,v); end
2 (Ex. 8) while Loops to find the minimum/maximum positive numbers represented in MATLAB%nm119_8.m: example of while loops x=1; k1=0; % To repeat division-by-2 to find the minimum positive number while x/2>0 x=x/2; k1=k1+1; end k1, x_min=x; fprintf('x_min is %20.18e\n',x_min) % To repeat multiplation-by-2 to find the maximum positive number x=1; k2=0; while 2*x<inf x=x*2; k2=k2+1; end k2, x_max0=x; tmp=1; k3=0; while x_max0*(2-tmp/2)<inf tmp=tmp/2; k3=k3+1; end k3, x_max=x_max0*(2-tmp); fprintf('x_max is %20.18e\n',x_max) format long e, x_min,-x_min,x_max,-x_max format hex, x_min,-x_min,x_max,-x_max format shortThe following script “nm119_8.m” contains three while loops. In the first one, x=1 continues to be divided by 2 till just before reaching zero and it will hopefully end up with the smallest positive number that can be represented in MATLAB. In the second one, x=1 continues to be multiplied by 2 till just before reaching inf (the infinity defined in MATLAB) and seemingly it will get the largest positive number ( x_max0) that can be represented in MATLAB. But while this number reaches or may exceed inf if multiplied by 2 once more, it still is not the largest number in MATLAB (slightly less than inf) that we want to find. How about multiplying x_max0 by (2−1/2n)? In the third while loop, the temporary variable tmp starting with the initial value of 1 continues to be divided by 2 till just before x_max0*(2‐tmp) reaches inf and apparently it will end up with the largest positive number ( x_max) that can be represented in MATLAB.