加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift算法手记-5

发布时间:2020-12-14 07:20:27 所属栏目:百科 来源:网络整理
导读://// 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.viewDidLo
//
//  ViewController.swift
//  learn5
//
//  Created by myhaspl on 16/1/23.
//  Copyright (c) 2016年 myhaspl. All rights reserved.
//

import Cocoa
import Foundation

class 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!)/2
				let leftres:Double=comresult(leftbound!)
		        let rightres:Double=comresult(rightbound!)
				let centres:Double=comresult(center)
				if centres==0 {
					answer=center
					break
				}
				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/


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读