R绘图积分 [英] R plotting integral
问题描述
我在R中的积分函数有一些问题.我试图绘制积分vo,但看来我做得不正确.
I'm having some problems with integration function in R. I'm trying to plot the integral vo but it seems I'm not doing correctly.
t <- seq(0, 0.04, 0.0001)
vi <- function(x) {5 * sin(2 * pi * 50 * x)}
vo <- function(x) {integrate(vi, lower=0, upper=x)$value}
test_vect = Vectorize(vo, vectorize.args='x')
plot(t, vo(t)) # should be a cosine wave
plot(t, vi(t)) # sine wave
vo
应该是正弦波,但是使用test_vect
给我错误的绘图,而使用vo
直接给我错误 'x'和'y'的长度不同 .有人可以帮我解决这个问题吗?
vo
should be a sine wave but using test_vect
gives me wrong plot and using vo
directly gives error 'x' and 'y' lengths differ. Can anyone, please, help me on this matter?
推荐答案
您已经在那里.只需使用plot(t, test_vect(t))
.您不能使用vo
,因为integrate
不是矢量化函数.评估vo(0.002)
之类的单点没有问题,但是vo(t)
不能将其作为向量.这就是为什么我们要Vectorize(vo)(t)
.
You are already there. Just use plot(t, test_vect(t))
. You can't use vo
, as integrate
is not a vectorized function. There is no problem to evaluate a single point like vo(0.002)
, but you can not feed it a vector by vo(t)
. This is why we want Vectorize(vo)(t)
.
您说test_vect
没有给出正确的图.当然?我们可以分析积分:
You said that test_vect
is not giving the right plot. Sure? We can analytically compute the integral:
v <- function (x) (1-cos(100*pi*x)) / (20*pi)
然后我们进行比较:
sum(abs(v(t) - test_vect(t)))
# [1] 2.136499e-15
它们是相同的!
这篇关于R绘图积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!