[Fortran] 纯文本查看 复制代码
program solver
implicit none
real,external::getroot,polyeq
real::tol=0.0001
real::coeff(4)=(/-1.,1.,0.,-1./)!多项式系数向量
real::root
root=getroot(polyeq,coeff,4,0.,1.)!求根函数
write(*,*)root
end program
real function getroot(polyeq,coeff,n,a,b)
implicit none
real,external::polyeq
integer,intent(in)::n
real,intent(in)::coeff(n)
real::a,b
integer::i
real::root
do
if(abs((b-a)/2) .lt. 0.0001)exit
root=(b+a)/2
if(abs(polyeq(coeff,n,root)) .lt. 0.0001)exit
if(polyeq(coeff,n,a)*polyeq(coeff,n,root) .lt. 0.0)then
b=root
else
a=root
end if
end do
getroot=root
! return getroot
end function getroot
real function polyeq(coeff,n,x)!多项式
implicit none
integer,intent(in)::n
integer::i
real,intent(in)::coeff(n)
real,intent(in)::x
real::vec(n)
real::res=0.0
vec=[((x**(i-1)),i=1,n)]
res=res+dot_product(coeff,vec)
polyeq=res
! return polyeq
end function polyeq
[Fortran] 纯文本查看 复制代码
program solver
implicit none
real,external::getroot,polyeq
real::tol=0.0001
real::coeff(4)=(/-1.,1.,0.,-1./)!多项式系数向量
real::root,a=0.0,b=1.0
root=getroot(polyeq,coeff,4,a,b)!求根函数
write(*,*)root
end program