数据库的二分法查找

先创建函数
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
posted @ 2009-06-26 17:32  tony smith  阅读(474)  评论(1编辑  收藏  举报