I have to convert a fortran program to matlab and I'm facing a problem. Although the fortran results are correct when I run the matlab script stucks. I believe the problem is in the first IF statement. Am I missing something to my matlab conversion ? Thanks in advance.
This is the full program with results both in Fortran and Matlab. The latest version is @Rotem 's solution. I, also, tried to add the fix to f1 and f2 as @BenBarrowes mentioned but the program stucks again. Thanks in advance :)
Fortran version
program asxm_2
implicit none
real(8) a,b, par1, sum,sum1,sum2, x,x1,x2, h, f,fa,fb,f1,f2,par2,e
integer n,j,y,k
real(8), allocatable, dimension (:) :: partitionS, valueS, errorS
a=0.
b=5.+85
par1=100*(atan(b)-atan(a))
fa=100/(1+a**2)
fb=100/(1+b**2)
print*, 'METHOD SIMPSON'
do n=1,1000000
h=(b-a)/n
sum1=0.
sum2=0.
x1=a
x2=a
do j=1,n-1
k=j
if(k/2/=j/2.) then
if(j==1) x1=x1+h
if(j>1) x1=x1+2*h
f1=100/(1+x1**2)
sum1=sum1+f1
else
x2=x2+2*h
f2=100/(1+x2**2)
sum2=sum2+f2
endif
enddo
par2= (h/3)*(fa+4*sum1+2*sum2+fb)
e=par1-par2
if(abs(e)<=0.001) exit
enddo
y=n
allocate(partitionS(y),valueS(y), errorS(y))
do n=1,y
h=(b-a)/n
sum1=0.
sum2=0.
x1=a
x2=a
do j=1,n-1
k=j
if(k/2==j/2.) then
x2=x2+2*h
f2=100/(1+x2**2)
sum2=sum2+f2
else
if(j==1) x1=x1+h
if(j>1) x1=x1+2*h
f1=100/(1+x1**2)
sum1=sum1+f1
endif
enddo
partitionS(n)=n
valueS(n)= (h/3)*(fa+4*sum1+2*sum2+fb)
errorS(n)=par1-valueS(n)
enddo
print*, 'Below are the results'
print*, partitionS(y), valueS(y), errorS(y)
deallocate(partitionS, valueS, errorS)
end
Fortran Results
Below are the results
332.00000000000000 155.96759681601489 9.7047371403391480E-004
Matlab version
a = 0;
b = 5.+85;
par1 = 100*(atan(b)-atan(a));
fa = 100/(1+a.^2);
fb = 100/(1+b.^2);
fprintf('METHOD SIMPSON\n');
for n = 1:1000000
h=(b-a)/n;
sum1=0;
sum2=0;
x1 = a;
x2 = a;
for j = 1:n-1
k = j;
if fix(k/2) ~= j/2
if j == 1
x1 = x1+h;
end
if j > 1
x1 = x1+2*h;
end
f1 = 100/(1+x1.^2);
sum1 = sum1 + f1;
else
x2 = x2+2*h;
f2 = 100/(1+x2.^2);
sum2 = sum2 + f2;
end
end
par2 = (h/3)*(fa+4*sum1+2*sum2+fb);
e = par1 - par2;
if abs(e)<0.001
break;
end
end
y=n;
partitionS = zeros (n);
valueS= zeros (n);
errorS = zeros (n);
for n = 1:y
h=(b-a)/n;
sum1=0;
sum2=0;
x1=a;
x2=a;
for j = 1:n-1
k = j;
if fix(k/2) == j/2
x2 = x2 + 2*h;
f2 = 100/(1+x2.^2);
sum2 = sum2 + f2;
else
if j == 1
x1 = x1 + h;
end
if j > 1
x1 = x1 + 2*h;
end
f1 = 100/(1+x2.^2);
sum1 = sum1 + f1;
end
end
partitionS(n) = n;
valueS(n)= (h/3)*(fa+4*sum1+2*sum2+fb);
errorS(n)=par1-valueS(n);
end
fprintf('Below are the results\n');
fprintf('%.25f\n',partitionS(n));
fprintf('%.25f\n',valueS(n));
fprintf('%.25f\n',errorS(n));
MATLAB Results
Below are the results
332.0000000000000000000000000
174.0415303853845900000000000
-18.0729630956556660000000000