4. The derivative of a function $f(x)$ at $x$ can be approximated by the Newton's quotient
$$\frac{f(x+h) - f(x-h)}{2 * h},$$
where $h$ is a small number. Write a function to calculate the Newton's quotient for the function $f(x) = \exp(x)$. The function should take two scalar arguments, $x$ and $h$. Use a default value of $h = 1e-6$.
f<-function(x,h=1e-6){
f<-(exp(x+h)-exp(x-h))/(2*h)
return(f)
}
f(1)
exp(1)
f(1)-exp(1)
Test your function at the point $x=1$ using the default value of $h$, and compare to the true value of the derivative $f'(1) = e^1$.
5. A very useful feature in R is the ability to pass a function name as an argument.
Here is an example, where 2 is added to the value of a function, for three different functions $\exp(x)$, $\log(x)$, and $\sin(x)$, at selected points $x$.
test <- function(x, f) {
output <- f(x) + 2
return(output)
}
test(0, exp)
test(1, log)
test(0, sin)
test(pi/2,sin)
Modify your function from problem 4 so that you pass in the name of the function for which you want to approximate the derivative. Use the same default value for $h$, and approximate the derivative of $sin(x)$ at $x=\pi/4$, of $\log(x)$ at $x=2$, and of $\exp(x)$ at $x=1$.
R 牛顿商及参数传递求解
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 社区专家-Monster-XH 2023-04-10 18:03关注
基于Monster 组和GPT的调写:
函数 f(x) 在 x处的导数可以近似地表示为牛顿商其中 h是一个小的数。编写一个函数来计算函数 f(x) = \exp(x) 的牛顿商。该函数应该接受两个标量参数 x 和 h。使用默认值 h=1e-6。
f <- function(x, h=1e-6) { f <- (exp(x+h) - exp(x-h))/(2*h) return(f) } f(1) exp(1) f(1) - exp(1)
用默认值 h 在 x=1 处测试函数,并将其与导数的真实值 f'(1) = e^1 进行比较。
R 中非常有用的一个特性是能够将函数名作为参数传递。以下是一个示例,在选择的点 x 上,对三个不同的函数 \exp(x),$log(x) 和 \sin(x)的值加上了2。
test <- function(x, f) { output <- f(x) + 2 return(output) } test(0, exp) test(1, log) test(0, sin) test(pi/2, sin)
修改问题4中的函数,使其传递要近似导数的函数的名称。使用相同的默认值 $h$,并近似于在 $x=\pi/4 处的 sin(x),在 x=2 处的 \log(x) 和在 x=1处的 exp(x) 的导数。
f_newton <- function(f, x, h=1e-6) { df <- (f(x+h) - f(x-h))/(2*h) return(df) } f_newton(sin, pi/4) f_newton(log, 2) f_newton(exp, 1)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 AT89C51控制8位八段数码管显示时钟。
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 下图接收小电路,谁知道原理
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口