Will Martin
Will Martin

Reputation: 1023

How do I evaluate this exponential expression without divide-by-zero problems?

I am trying to avoid divide by zero errors for the following expression,

(1-exp(-a)) / a.

When a=0 the expression should return 1. I could use the expm1 function to avoid truncation error, but division by zero still causes a problem.

Is there a function like expm1 but with the division by a?

Upvotes: 0

Views: 61

Answers (2)

Tristan Schuler
Tristan Schuler

Reputation: 41

Use an if else statement for your case.

Upvotes: 2

Will Martin
Will Martin

Reputation: 1023

Notice that you can rewrite the expression as,

(1-exp(-a)) / a = exp(-a/2) * sinh(a/2) / (a/2)
                ~ exp(-a/2) * (1 + 1/6 * (a/2)**2 + 1/120 * (a/2)**4)

If abs(a)>=1e-4 use the original expression, else use the approximation.

Upvotes: 0

Related Questions