[英]Return integrated function using R
Let's say i have a function defined as the following in R: 假设我在R中定义了以下函数:
> f <- function(x) 0.5*sin(x)*(x>=0)*(x<=pi)
i can do this to integrate it between 0 and pi: 我可以这样做以将其在0和pi之间进行积分:
> Integrate <- function(f,a,b) integrate(Vectorize(f),a,b)$value
> F <- Integrate(f,0,pi)
But if i want to evaluate and return some values of F i get this error: 但是,如果我想评估并返回F的一些值,则会出现此错误:
> F(c(-100,0,1,2,pi,100))
Error in F(c(-100, 0, 1, 2, pi, 100)) :
function "F" is not found
i can understand that this is due to the fact, that my integrate <- function(f,a,b) returns a constant value C which is the result of the integration of f between a and b, but how can i return F as a function to be able to evaluate it's values as a vector and plot it ? 我可以理解这是由于以下事实:我的积分<-函数(f,a,b)返回一个常数C,这是f在a和b之间积分的结果,但是我怎么能返回F为一个能够将其值作为向量求值并将其绘制的函数?
like in this case F should give 0 for any value less than 0 and 1 for any value bigger than pi and be variable between them. 像在这种情况下,对于小于0的任何值,F应该给0;对于大于pi的任何值,F应该给1,并且可以在它们之间变化。
Thanks. 谢谢。
Edit: just to sum it up more clearly: how can i define a function f(x) in [a,b] that will give me f(x) if x is in [a,b], 0 if xb ? 编辑:只是为了更清楚地总结一下:如何在[a,b]中定义函数f(x),如果x在[a,b]中将给我f(x),如果xb是0?
Try wrapping your function call in an sapply
and have Integrate return a function. 尝试将函数调用包装在一个sapply
并让Integrate返回一个函数。
Integrate <- function(f, a, b) function(x) if (x < a) 0 else if (x > b) 1 else integrate(Vectorize(f), a, x)$value
F <- Integrate(f, 0, pi)
sapply(c(-100,0,1,2,pi,100), F)
gives 给
[1] 0.0000000 0.0000000 0.2298488 0.7080734 1.0000000 1.0000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.