先建立函數
create function F(@y float,@c float,@f float,@pv float,@m float,@n int,@d float)
returns float
as
begin
declare @i int
declare @ret float
set @i=0
set @ret=0
while @i<@n
begin
set @ret=@ret+(@c/@f)*Power(@f/(@f+@y),@d/365*@f+@i)
set @i=@i+1
end
set @ret=@ret+@m*Power(@f/(@f+@y),@d/365*@f+@n-1)-@pv
return @ret
end
接著再用二分法計算,下面的過程可以寫成預存程序,資料的輸入你可以從表中讀取,如果一次要計算表中多行資料,就用遊標
declare @c float,@f float,@pv float,@m float,@n int,@d float
declare @yh float,@yl float,@fm float,@e float,@fh float,@fl float
/*賦值略
set @c=?
set @f=?
……*/
set @fh=dbo.F(@yh)
set @fl=dbo.F(@yl)
if @fh*@fl>=0 select '資料錯誤'
else begin
while abs(@yh-@yl)>@e
begin
set @fm=dbo.F((@yh+@yl)/2)
if @fm=0 break
if @fm*@fh<0
begin
set @yl=(@yh+@yl)/2
set @fl=@fm
end
else
if @fm*@fl<0
begin
set @yh=(@yh+@yl)/2
set @fh=@fm
end
end
select (@yh+@yl)/2
end