R绘图积分 [英] R plotting integral

查看:197
本文介绍了R绘图积分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆