gpt4 book ai didi

ios - swift 中的微分函数?

转载 作者:IT王子 更新时间:2023-10-29 05:39:32 26 4
gpt4 key购买 nike

我想为我的应用程序的一部分创建一个函数,该函数返回函数在某个点的导数。显然,这是极限的正式定义。

enter image description here

但是什么样的函数能够快速返回函数在某一点的导数呢?有什么关于 swift 自动微分的想法吗?

最佳答案

这是一个基于上述公式的简单数值方法。您可以对此进行改进:

derivativeOf 采用函数 fn 和 x 坐标 x 并返回 fn 的导数的数值近似值> 在 x:

func derivativeOf(fn: (Double)->Double, atX x: Double) -> Double {
let h = 0.0000001
return (fn(x + h) - fn(x))/h
}

func x_squared(x: Double) -> Double {
return x * x
}

// Ideal answer: derivative of x^2 is 2x, so at point 3 the answer is 6
let d1 = derivativeOf(fn: x_squared, atX: 3) // d1 = 6.000000087880153

// Ideal answer: derivative of sin is cos, so at point pi/2 the answer is 0
let d2 = derivativeOf(fn: sin, atX: .pi/2) // d2 = -4.9960036108132044e-08

如果您计划从用户那里获得功能,那将是比较困难的部分。您可以给他们一些模板供他们选择:

  1. 三阶多项式:y = Ax^3 + Bx^2 + Cx + D
  2. 正弦函数:y = A * sin(B*x + C)
  3. cos 函数:y = A * cos(B*x + C)
  4. n 次根:y = x ^ (1/N)

等然后你可以让他们给你 A、B、C、D 或 N

让我们看看这对于三阶多项式是如何工作的:

// Take coefficients A, B, C, and D and return a function which
// computes f(x) = Ax^3 + Bx^2 + Cx + D
func makeThirdOrderPolynomial(A a: Double, B b: Double, C c: Double, D d: Double) -> ((Double) -> Double) {
return { x in ((a * x + b) * x + c) * x + d }
}

// Get the coefficients from the user
let a = 5.0
let b = 3.0
let c = 1.0
let d = 23.0

// Use the cofficents to make the function
let f4 = makeThirdOrderPolynomial(A: a, B: b, C: c, D: d)

// Compute the derivative of f(x) = 5x^3 + 3x^2 + x + 23 at x = 5
// Ideal answer: derivative is f'(x) = 15x^2 + 6x + 1, f'(5) = 406
let d4 = derivativeOf(fn: f4, atX: 5) // d4 = 406.0000094341376

关于ios - swift 中的微分函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31014918/

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