r/AskComputerScience • • May 03 '21

Whys is there a function for e^x -1

Very, very new to coding, just learnt about functions; decided to read through the list of math functions. I was surprised to learn about expm1.

Why is there a specific function for this to provide more accuracy when x is small? I didn't realise it would be such a common computation; it seems very arbitrary to me.

(sorry if this is the wrong sub for this q, if so please redirect me)

42 Upvotes

9 comments sorted by

36

u/[deleted] May 03 '21

The IEEE explained the reasoning here:

https://pubs.opengroup.org/onlinepubs/009695399/functions/expm1.html

It shows up a lot in financial calculations and certain kinds of trigonometric functions.

2

u/13walshc May 03 '21

Just what I was looking for thanks.

20

u/teraflop May 03 '21

Why is there a specific function for this to provide more accuracy when x is small?

/u/Al3xR3ads gave you some examples of where this is useful, but also: I think "more accuracy" is kind of under-selling it.

Typically, floating-point operations like exp and expm1 are specified to be accurate to within something like 1 ULP ("unit in the last place", i.e. the value of the least-significant binary digit). This means the relative error of the result (as a percentage of the "ideal" value) is bounded.

In contrast, if you compute exp(x)-1 where x is close to zero, the intermediate result of exp(x) is very close to one. This means a small error in exp(x) can result in a proportionately much larger error in the final result, because of catastrophic cancellation. In particular, the relative error gets worse as x approaches zero. If x is less than about 10-16 then the relative error is above 100%, and your computation is basically useless.

Conversely, exp(x) can have much better relative error than expm1(x)+1 if x is negative with a non-trivial magnitude. So it's nice to have both functions available.

4

u/13walshc May 03 '21

Thanks. I think this sort of direction is where my questions were about to lead. Think ill have to do abit of reading about catastrophic cancellation though since I haven't learnt about anything like that before.

3

u/jeffbell May 04 '21

Awesome question btw. 35 years in the business and I hadn’t thought about it.

2

u/13walshc May 04 '21 edited May 04 '21

thanks, I think its often the case with questions coming from a place of ignorance that they can take a perspective you hadn't considered. my lucky gift of ignorance haha.

3

u/13walshc May 03 '21

similarly for log1px

3

u/jeffbell May 04 '21

It’s the inverse function of expm1

1

u/13walshc May 04 '21

ye ye ik, I meant that the 'similarly' as in the question and, as I was guessing when I wrote it, the answer could also be applied to expm1