gpt4 book ai didi

Swift自动函数反转

转载 作者:行者123 更新时间:2023-11-28 11:16:35 32 4
gpt4 key购买 nike

如果我有这样的功能:

func evaluateGraph(sender: GraphView, atX: Double) -> Double? {
return function?(atX)
}

其中 function 是之前声明的变量,它是一个数学表达式(如 x^2)。如何在 swift 中找到单变量 function 的反函数(atX)?

最佳答案

假设您只想知道 GraphView 中的反函数(希望它不是无限的),您可以使用这样的东西:

// higher percision -> better accuracy, start...end: Interval, f: function
func getZero(#precision: Int, var #start: Double, var #end: Double, f: Double -> Double) -> Double? {

let fS = f(start)
let fE = f(end)

let isStartNegative = fS.isSignMinus
if isStartNegative == fE.isSignMinus { return nil }

let fMin = min(fS, fE)
let fMax = max(fS, fE)

let doublePrecision = pow(10, -Double(precision))

while end - start > doublePrecision {
let mid = (start + end) / 2
let fMid = f(mid)
if fMid < fMin || fMax < fMid {
return nil
}
if (fMid > 0) == isStartNegative {
end = mid
} else {
start = mid
}
}

return (start + end) / 2
}

// same as above but it returns an array of points
func getZerosInRange(#precision: Int, #start: Double, #end: Double, f: Double -> Double) -> [Double] {

let doublePrecision = pow(10, -Double(precision))

/// accuracy/step count between interval; "antiproportional" performance!!!!
let stepCount = 100.0
let by = (end - start) / stepCount
var zeros = [Double]()

for x in stride(from: start, to: end, by: by) {
if let xZero = getZero(precision: precision, start: x, end: x + by, f) {
zeros.append(xZero)
}
}
return zeros
}

// using currying; all return values should be elements of the interval start...end
func inverse(#precision: Int, #start: Double, #end: Double, f: Double -> Double)(_ x: Double) -> [Double] {
return getZerosInRange(precision: precision, start: start, end: end) { f($0) - x }
}

let f = { (x: Double) in x * x }

// you would pass the min and max Y values of the GraphView
// type: Double -> [Double]
let inverseF = inverse(precision: 10, start: -10, end: 10, f)

inverseF(4) // outputs [-1.999999999953436, 2.000000000046564]

有趣的是,这段代码在 playground 中运行了大约 0.5 秒,这出乎我的意料。

关于Swift自动函数反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372984/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com