My bisection method is freezing when I put smaller error margin.
Show older comments
When I put error margin smaller than 0.1, it keeps going but never stops.
clc; clear all; close all;
D= 4*0.0254; %inner diameter (inch to meter)
radius=D/2;
Q= (2000 * 42 * 3.785e-3) / 86400 ; %Volumetric flow rate (bbl to gal to m^3) / (day to second)
area= pi*((radius)^2); %cross sectional area
p= 0.9 * 1000; %density (g/cm^3 to kg/m^3)
Mu= 8 * 0.001 %viscosity (cp to pa*s)
e_D=[0,0.002,0.004,0.006,0.008];
Re=linspace(5000,100000,5); %Reynolds number
z=@(x)(-2.0).*log10(((e_D)./3.7)+(2.51./(Re.*sqrt(x))))-(1./sqrt(x)); %friction factor
%bisection method
error=1e-8;
a=0;
b=1;
c=(a+b)./2;
while abs(z(c))>error
if z(a).*z(c)<0
b=c;
else
a=c;
end
c=(a+b)./2;
end
Answers (1)
Your function z does not return a scaler output for a scalar input x since e_D and Re are vectors. for bisection method to work, z(x) is a scalar function.
D= 4*0.0254; %inner diameter (inch to meter)
radius=D/2;
Q= (2000 * 42 * 3.785e-3) / 86400 ; %Volumetric flow rate (bbl to gal to m^3) / (day to second)
area= pi*((radius)^2); %cross sectional area
p= 0.9 * 1000; %density (g/cm^3 to kg/m^3)
Mu= 8 * 0.001 %viscosity (cp to pa*s)
e_D=[0,0.002,0.004,0.006,0.008];
e_D = 0;
Re=linspace(5000,100000,5); %Reynolds number
Re = 5000;
z=@(x)(-2.0).*log10(((e_D)./3.7)+(2.51./(Re.*sqrt(x))))-(1./sqrt(x)); %friction factor
z(1)
%bisection method
error=1e-8;
a=0;
b=1;
c=(a+b)./2;
i= 0;
while abs(z(c))>error
if z(a).*z(c)<0
b=c;
else
a=c;
end
fprintf("a=%f b=%f c=%f z(c)=%f\n", a, b, c, z(c));
%if i>50, break; end
c=(a+b)./2;
i = i+1;
end
fplot(z, [-1 1]); grid on
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!