用牛顿迭代法计算附息式国债的收益率(matlab函数版)

时间:2022-11-09 19:01:54

用牛顿迭代法计算附息式国债的收益率(matlab函数版)

  • main函数

%main.m
clear;
a=155.45;
b=11.83;
d=100.0;
k=6;
e=0.85;
f=1.1;
g=0.00001;

x=gznewton(a,b,d,k,e,f,g)-1;
fprintf('SYL is %f\n',x);
  • gznewton函数
%gznewton.m
%gznewton(a,b,d,k,e,f,g)
function product=gznewton(p0,c,m,n,t,y0,wc)
done=0;
y=y0;

while 1
    fy=p0*power(y,n+t)-c-m;
    fy1=p0*(n + t)*power(y,n+t-1);
    for i=0:1:n-1
       fy=fy-c*power(y,n-i);
       fy1=fy1-c*(n-i)*power(y,n-i-1);
    end

    if fy1 ~= 0
       newton=y-fy/fy1;
       if(abs(newton-y)<wc || abs(newton-y0)>0.2)
           done=1;
       else
           y=newton;
       end
    else
        done=1;
        fprintf('down=%d\n',done);
    end

    if done
        break;%跳出循环
    end       
end
 %return newton;
product=newton;