简体   繁体   English

在 R 中绘制一个困难的函数并通过二等分找到根

[英]Plot a difficult function in R and find the root by bisection

eq <- function(x){ sum(exp(-Ln.M_Return[,1]/x)) / 168 - 1 } 
# Ln.M_Return[,1] is a vector of stock return, and its length is 168.

My first goal is to draw the plot for this function.我的第一个目标是为这个函数画图。 However, there is always an error here.但是,这里总是有错误。 When I use "curve" function,当我使用“曲线”功能时,

curve(eq(x))

it will appear an error message:会出现错误信息:

Error in curve(eq(x)) : 'expr'
In addition: Warning message:
In -Ln.M_Return[, 1]/x :
  longer object length is not a multiple of shorter object length

I have tried some other methods, like plot() and xyplot(), but nothing changed.我尝试了其他一些方法,例如 plot() 和 xyplot(),但没有任何改变。

My main purpose is actually using bisection method to find the root of the function, which is the formula of Aumann-Serrano riskiness index.我的主要目的实际上是使用二分法求函数的根,也就是 Aumann-Serrano 风险指数的公式。 Thus, I choose to draw the plot first and approximate the location of the root.因此,我选择先绘制图并近似根的位置。 Then I will use some codes of bisection to find the root.然后我将使用一些二分代码来找到根。 Thanks for reading my question patiently!感谢您耐心阅读我的问题!

Without having your Ln.M_Return , I created some random data.没有你的Ln.M_Return ,我创建了一些随机数据。 You should Vectorize your equation in the curve function like this:你应该像这样在curve函数中向Vectorize你的方程:

Ln.M_Return <- runif(168,0,10)
Ln.M_Return <- as.data.frame(Ln.M_Return)

eq <- function(x){ sum(exp(-Ln.M_Return[,1]/x)) / 168 - 1 } 

g <- Vectorize(eq)

curve(g, from=1, to=100, , xlab="xvalue", ylab="yvalue", 
      col="blue", lwd=2)

Output:输出:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM