代码之家  ›  专栏  ›  技术社区  ›  Mathlete

如何绘制计算PDF的函数?

  •  0
  • Mathlete  · 技术社区  · 12 年前

    这就是我的函数计算的PDF:

    fx=0.3如果(0<=x<1) 0.1如果(1<=x<2) 0.25如果(2<=x<3) 0.15如果(3<=x<4) 0.2如果(4<=x<5) 0否则


    这是我对它的编码:

        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呢?
    我尝试过:

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

    但我得到一个错误,“x”和“y”的长度不同?

    2 回复  |  直到 12 年前
        1
  •  6
  •   Community CDub    8 年前

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

    如果您使用 accepted solution 从你之前关于 完全相同的问题 那么你就不会有任何问题了

    # 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

    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)')
    

    enter image description here

    如果你不想增加分数,那么

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

    如果要对阶跃函数进行矢量化,请使用 Vectorize

     vfx <- Vectorize(fx)
    
        2
  •  1
  •   Matthew Lundberg    12 年前

    您的PDF没有矢量化。试试这个:

    fx <- function(x) {
      ifelse((0<=x) & (x<1), 0.3,
      ifelse((1<=x) & (x<2), 0.1,
      ifelse((2<=x) & (x<3), 0.25,
      ifelse((3<=x) & (x<4), 0.15,
      ifelse((4<=x) & (x<5), 0.2,
      0)))))
    }
    
    x <- seq(0, 6, length.out=n)
    plot(x, fx(x))