Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 分裂法算法_Swift_Algorithm_Math - Fatal编程技术网

Swift 分裂法算法

Swift 分裂法算法,swift,algorithm,math,Swift,Algorithm,Math,(x^3-2x^2-5)是我的等式。首先,我有两个值,如x=2和x=4。我的前两个值必须是等式的计数,每次结果必须是负数和正数。第二步是方程中的(2+4)/2=3,这次x=3。数学运算以最后一个正值和一个负值继续。我试试这个 var x = 2.0 var equation = pow(x, 3) - 2 * pow(x, 2) - 5 switch x { case x : 2 equation = pow(x, 3) - 2 * pow(x, 2) - 5 case x : 4 equat

(x^3-2x^2-5)
是我的等式。首先,我有两个值,如
x=2和x=4。
我的前两个值必须是等式的计数,每次结果必须是负数和正数。第二步是方程中的
(2+4)/2=3
,这次
x=3
。数学运算以最后一个正值和一个负值继续。我试试这个

var x = 2.0
var equation = pow(x, 3) - 2 * pow(x, 2) - 5

switch x {
case x : 2
equation = pow(x, 3) - 2 * pow(x, 2) - 5
case x : 4
equation = pow(x, 3) - 2 * pow(x, 2) - 5
default:
0
}  
print(equation)

如何为一个
var x
分配前两个值,如2和4?

显然,您希望实现查找方程(实)解(“根”)的方法。第一步是将该方程定义为一个函数,以便可以在不同点对其进行计算:

func f(_ x: Double) -> Double {
    return pow(x, 3) - 2 * pow(x, 2) - 5
}
然后需要两个变量作为当前间隔的左边界和右边界。这些符号的选择必须确保
f(x)
在边界处有相反的符号。在您的示例中:

var xleft = 2.0   // f(xleft) < 0
var xright = 4.0  // f(xright) > 0

下一步是将二分法本身作为一个函数来实现:

func bisect(_ f: ((Double) -> Double), xleft: Double, xright: Double, eps: Double = 1.0e-6) -> Double {
    let yleft = f(xleft)
    let yright = f(xright)

    precondition(yleft * yright <= 0, "f must have opposite sign at the boundaries")

    var xleft = xleft
    var xright = xright

    repeat {
        let x = (xleft + xright)/2.0
        let y = f(x)
        if y == 0 {
            return x
        } else if y.sign == yleft.sign {
            xleft = x
        } else {
            xright = x
        }
    } while xright - xleft > eps

    return (xleft + xright)/2.0
}

因此,您想实现以找到方程x^3-2x^2-5=0的解?第一步是将该方程定义为一个函数:
func f(x:Double)->Double{…}
Yes二分法看起来是一样的
func bisect(_ f: ((Double) -> Double), xleft: Double, xright: Double, eps: Double = 1.0e-6) -> Double {
    let yleft = f(xleft)
    let yright = f(xright)

    precondition(yleft * yright <= 0, "f must have opposite sign at the boundaries")

    var xleft = xleft
    var xright = xright

    repeat {
        let x = (xleft + xright)/2.0
        let y = f(x)
        if y == 0 {
            return x
        } else if y.sign == yleft.sign {
            xleft = x
        } else {
            xright = x
        }
    } while xright - xleft > eps

    return (xleft + xright)/2.0
}
let sol1 = bisect({ x in pow(x, 3) - 2 * pow(x, 2) - 5 }, xleft: 2.0, xright: 4.0)
print(sol1) // 2.690647602081299

let sol2 = bisect({ x in cos(x/2)}, xleft: 3.0, xright: 4.0, eps: 1.0e-15)
print(sol2) // 3.1415926535897936