作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我想为我的应用程序的一部分创建一个函数,该函数返回函数在某个点的导数。显然,这是极限的正式定义。
但是什么样的函数能够快速返回函数在某一点的导数呢?有什么关于 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
如果您计划从用户那里获得功能,那将是比较困难的部分。您可以给他们一些模板供他们选择:
y = Ax^3 + Bx^2 + Cx + D
y = A * sin(B*x + C)
y = A * cos(B*x + C)
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/
我正在为仪表板创建径向仪表。以下代码是我的工作。我需要知道如何使起始 Angular 为 15 度以及如何使结束 Angular 为 165 度。请帮助我。我需要实现这个系统,所以期待完成这项工作。我
我是一名优秀的程序员,十分优秀!