Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save hdavid0510/7ff9b2a140a6a5464c9b5a018b5cc1e8 to your computer and use it in GitHub Desktop.

Select an option

Save hdavid0510/7ff9b2a140a6a5464c9b5a018b5cc1e8 to your computer and use it in GitHub Desktop.

Revisions

  1. hdavid0510 created this gist Apr 2, 2021.
    43 changes: 43 additions & 0 deletions ku2021_mech457_hw1_q8_approximation.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    clc, clear, close('all')

    %% PLOT
    x = -4:0.1:8;
    plot(x, ku2021_mech457_hw1_q8_f(x))
    xlabel('x'); ylabel('y');
    title('f(x) = -0.6*x^2 + 2.4*x + 5.5');
    hold on, plot([x(1), x(end)], [0,0], 'k')
    clear x

    %% LEFT root; -4 <= \alpha < 2
    fprintf('Find LEFT root:\n');
    x_l = -4;
    x_r = 2;
    for j=1:6
    x = x_l:0.1^j:x_r;
    for i=1:length(x)
    if(ku2021_mech457_hw1_q8_f(x(i)) * ku2021_mech457_hw1_q8_f(x(i+1)) <0)
    x_l = x(i);
    x_r = x(i+1);
    fprintf('x_l#%d=%f\tf(x_l)=%f\tx_r#%d=%f\tf(x_l)=%f\n',j,x_l,q8_f(x_l),j,x_r,ku2021_mech457_hw1_q8_f(x_r));
    clear x
    break
    end
    end
    end

    %% RIGHT root; 2 < \beta <= 8
    fprintf('Find RIGHT root:\n');
    x_l = 2;
    x_r = 8;
    for j=1:6
    x = x_l:0.1^j:x_r;
    for i=1:length(x)
    if(ku2021_mech457_hw1_q8_f(x(i)) * ku2021_mech457_hw1_q8_f(x(i+1)) <0)
    x_l = x(i);
    x_r = x(i+1);
    fprintf('x_l#%d=%f\tf(x_l)=%f\tx_r#%d=%f\tf(x_l)=%f\n',j,x_l,q8_f(x_l),j,x_r,ku2021_mech457_hw1_q8_f(x_r));
    clear x
    break
    end
    end
    end
    38 changes: 38 additions & 0 deletions ku2021_mech457_hw1_q8_bisection.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    clc, clear, close('all')
    x_l = 5;
    x_u = 10;
    x_TRUE = (12+sqrt(474))/6;

    x = [x_l x_u];
    y = ku2021_mech457_hw1_q8_f(x);

    i = 0;
    err_apprx = 1000;
    while i<=3
    i = i+1;
    fprintf('[iteration #%d] ',i);

    xnew(i) = mean(x);
    ynew = ku2021_mech457_hw1_q8_f(xnew(i));

    if y(1)*ynew > 0
    x = [xnew(i), x(2)];
    y = ku2021_mech457_hw1_q8_f(x);
    elseif y(1)*ynew < 0
    x = [x(1), xnew(i)];
    y = ku2021_mech457_hw1_q8_f(x);
    else
    fprintf('the solution is %f\n', xnew(i));
    break
    end

    if i > 1
    err_apprx = 100*abs((xnew(i) - xnew(i-1))/xnew(i));
    err_true = abs(mean(x) - x_TRUE);
    fprintf('x=[%f,%f]\tepsilon_a=%f\tepsilon_t=%f ', x(1), x(2), err_apprx, err_true);
    end

    fprintf('\n');
    end
    fprintf('solution = %f\n', xnew(end));
    clear x y xnew i e
    3 changes: 3 additions & 0 deletions ku2021_mech457_hw1_q8_f.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    function y = ku2021_mech457_hw1_q8_f(x)

    y = -0.6*x.^2 + 2.4*x + 5.5;