如何绘制一个计算PDF的函数? [英] How to plot a function that calculates the PDF?

查看:37
本文介绍了如何绘制一个计算PDF的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的函数计算的PDF:

So this is the PDF that my function calculates:

fx = 0.3如果(1< = x< 2),则为0.1如果(2< = x< 3),则为0.25如果(3< = x< 4),则为0.15如果(4 <= x <5)为0.20否则

fx = 0.3 if (0<=x<1) 0.1 if (1<=x<2) 0.25 if (2<=x<3) 0.15 if (3<=x<4) 0.2 if (4<=x<5) 0 otherwise


这是我的编码:


And this is my coding for it:

    fx = function(x)
    { 
    if ((0<=x) & (x<1)) 0.3
    else if ((1<=x) & (x<2)) 0.1
    else if ((2<=x) & (x<3)) 0.25
    else if ((3<=x) & (x<4)) 0.15
    else if ((4<=x) & (x<5)) 0.2
    else 0
    }


现在我该如何绘制y = fx?
我尝试过:


Now how would I go about plotting y=fx?
I've tried:

    x <- runif(n,0,5)
    y <- fx(x)
    plot(x, y, type='1', xlim=c(0,5), ylim=c(0,5))

但是我收到一个错误,指出'x'和'y'的长度不同?

But I get an error that 'x' and 'y' have differing lengths?

推荐答案

您的问题归结为您的函数没有正确向量化(不能很好地处理向量).

Your problems comes down to the fact your function isn't vectorized properly (it doesn't deal with a vector well).

如果您使用之前关于完全相同的问题的问题中的接受的解决方案,则您不会有任何问题

If you use the accepted solution from your previous question about exactly the same problem then you won't have any issues

例如

# a solution that will work and be properly vectorized
fx <- function(x) c(0, 0.3,0.1,0.25,0.15,0.20, 0)[findInterval(x, c(-Inf, 0:5, Inf))]


 x <- runif(n,0,5)

plot(x, fx(x))

如果要绘制步进函数(此pdf就是这样),则可以使用 stepfun

If you want to plot a step function (which is what this pdf is), you can use stepfun

例如

fx <- stepfun(x = 0:5, y = c(0,0.3,0.1,0.25,0.15,0.20,0))
plot(fx, ylim = c(0,0.4),xlim = c(0,5), main = 'f(x)')

如果您不想添加点,那么

If you don't want the points added then

plot(fx, ylim = c(0,0.4),xlim = c(0,5), main = 'f(x)', do.points=FALSE)

如果要对步函数进行矢量化处理,请使用 Vectorize

If you want to vectorize a step function, then use Vectorize

 vfx <- Vectorize(fx)

这篇关于如何绘制一个计算PDF的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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