本文主要是介绍swift算法手记-7,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
@IBAction func compute(sender: AnyObject) {// 19*x^7-31*x^5+16*x^2+7*x-90=0// newton迭代法求一元方程的解,最大求解范围[-100000,100000]mytitle.stringValue="19*x^7-31*x^5+16*x^2+7*x-90=0"let trycount = 120var accuracy: Double = 1e-15var answer: Double?=nil// 估计解范围var leftbound:Double?=nilvar rightbound:Double?=nilfor var bound:Double=1;bound<10000000;bound*=10{let leftres=comresult(-bound)let rightres=comresult(bound)if (leftres*rightres) < 0 {leftbound = (-bound)rightbound = boundbreak}else if leftres==0{answer=leftboundbreak}else if rightres==0{answer=rightboundbreak}}if (leftbound==nil || rightbound==nil){return}var center=leftbound!+(rightbound!-leftbound!)/2let centres:Double=comresult(center)if centres==0 {answer=center}if centres*comresult(rightbound!)<0{leftbound=center}else if centres*comresult(leftbound!)<0{rightbound=center}if answer==nil{//计算方程的解var p0=leftbound!+(rightbound!-leftbound!)/2 var p:Doublefor i in 1...trycount{p = newtoncompresult(p0)if abs(p-p0) < accuracy {answer=p0break}p0=p}}if let ans=answer{//方程有解result.stringValue="解:"+String(stringInterpolationSegment: ans)+" "result.stringValue += "解代入方程的值:"+String(stringInterpolationSegment:comresult(ans))} }
用牛顿迭代法解非线性方程
本博客所有内容是原创,如果转载请注明来源
http://blog.csdn.net/myhaspl/
这篇关于swift算法手记-7的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!