swift演算法手記-5

來源:互聯網
上載者:User

標籤:height   tar   inter   repr   com   loaded   ids   setup   tracking   

////  ViewController.swift//  learn5////  Created by myhaspl on 16/1/23.//  Copyright (c) 2016年 myhaspl. All rights reserved.//import Cocoaimport Foundationclass ViewController: NSViewController {    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.    }    override var representedObject: AnyObject?

{ didSet { // Update the view, if already loaded. } }private func comresult(inputnum:Double)->Double{ // 5*x^7-3*x^5+16*x^2+7*x+90=0 let myresult:Double = 5 * pow(inputnum,7) - 3 * pow(inputnum,5) + 16 * pow(inputnum,2) + 7 * inputnum + 90 return myresult} @IBOutlet weak var result: NSTextField! @IBAction func compute(sender: AnyObject){// 5*x^7-3*x^5+16*x^2+7*x+90=0// 二分法求一元方程的解,最大求解範圍[-100000,100000] let trycount = 80 var accuracy: Double = 0.00000000000001 var answer: Double?

=nil // 預計解範圍 var leftbound:Double?=nil var rightbound:Double?=nil for var bound:Double=1;bound<10000000;bound*=10{ let leftres=comresult(-bound) let rightres=comresult(bound) if (leftres*rightres) < 0 { leftbound = (-bound) rightbound = bound break } } if (leftbound==nil || rightbound==nil){ return } //計算方程的解 for i in 1...trycount{ result.stringValue=String(i) let center=leftbound!+(rightbound!-leftbound!)/2let leftres:Double=comresult(leftbound!) let rightres:Double=comresult(rightbound!)let centres:Double=comresult(center)if centres==0 {answer=centerbreak}else if abs(rightbound!-leftbound!) < accuracy {answer=leftbound!break}else if leftres*centres<0{rightbound=center}else if rightres*centres<0{leftbound=center} } if let ans=answer{//方程有解 result.stringValue="解:"+String(stringInterpolationSegment: ans)+" " result.stringValue += "解代入方程的值:"+String(stringInterpolationSegment:comresult(ans)) } }}



本部落格全部內容是原創。假設轉載請註明來源http://blog.csdn.net/myhaspl/

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />

swift演算法手記-5

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.