Search code examples
rexp

Exponential function in R returning 0 as a value


who can tell me a solution to avoid a result of 0 in y in R program

y= 1-(1/(1+exp(-x)))

exp(-x) is > 0 but for x values like 100 the result of y is 0. I need to get small numbers > 0 to apply log(y) without getting -Inf result.


Solution

  • You can solve this with some simple maths:

    x <- 1
    1-(1/(1+exp(-x)))
    #[1] 0.2689414
    1/(exp(x) + 1)
    #[1] 0.2689414
    
    x <- 100
    1-(1/(1+exp(-x)))
    #[1] 0
    1/(exp(x) + 1)
    #[1] 3.720076e-44
    

    If you are interested in log(y) for large values of x, just ignore the + 1, y is approximately exp(-x) with a very small error for large x. Thus, log(y) == -x for large x.

    Your teacher probably wants you to do the maths.