Ku-trala
Ku-trala

Reputation: 651

Returning NaN instead of -1

I'm trying to maximize a function and in my code in R I use the following function to make sure, that I get a value of A, which is between -1 and 1:

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

The problem is that, when I for instance evaluate the function at x=3000 or some other extreme value, it returns NaN instead of -1, which it should.

Is there a way to write up this to make sure, this does not happen?

Thanks.

Upvotes: 2

Views: 410

Answers (2)

Randy Lai
Randy Lai

Reputation: 3174

You can do a little math

enter image description here

so that, A = 1 - 2/(exp(x)+1) will do the job.

When x is large, exp(x) equals Inf, such that 2/(exp(x)+1) is 0.

It is a very handy feature of R, but the implementation costs too much computational power. Sometimes, these are be blamed for slow speed of R.

Upvotes: 6

AGS
AGS

Reputation: 14498

The logit and probit functions will return values between 0 and 1. You might consider using the hyperbolic tangent,

(1 - exp(-2*x)) / (1 + exp(-2*x))

which will return a value between -1 and 1. In your case, you are dividing by INF when x goes above ~700, thus returning a NAN.

Upvotes: 4

Related Questions