Swift algorithm note-5
//// 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 // returns the solution of the one-dimensional equation using the bipartite method, the maximum solution range is [-100000,100000] let trycount = 80 var accuracy: Double = 0.00000000000001 var answer: Double? = Nil // estimated Solution Range: 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} // calculate the equation solution 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 {// The equation has a solution result. stringValue = "solution:" + String (stringInterpolationSegment: ans) + "result. stringValue + = "value for resolving the substituted equation:" + String (stringInterpolationSegment: comresult (ans ))}}}