Mine
Mine

Reputation: 861

Getting 0 in R instead of a precise result

How can I get the actual precise result instead of the rounded ones?

result = ((0.61)**(10435)*(0.39)**(6565))/((0.63)**(5023)*(0.60)**(5412)*(0.37)**(2977)*(0.40)**(3588))

out:

NaN

Because, denominator is 0

Upvotes: 3

Views: 201

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101335

I think logarithm is a power tool to deal with exponential with large powers (see it properties in https://mathworld.wolfram.com/Logarithm.html)

You can try to use log first over your math expression and then apply exp in turn, i.e.,

result <- exp((10435*log(0.61)+6565*log(0.39)) - (5023*log(0.63)+5412*log(0.60)+ 2977*log(0.37)+3588*log(0.40)))

which gives

> result
[1] 0.001219116

Upvotes: 7

user2332849
user2332849

Reputation: 1450

R cannot handle such large exponents because that will converge to 0 beyond its precision. Precision is not infinite. For what you want, you need an arbitrary precision package, such as Rmpfr.

library(Rmpfr)

precision <- 120

result <- (mpfr(0.61, precision)**10435 * mpfr(0.39, precision)**6565) /
  (mpfr(0.63, precision)**5023 * mpfr(0.60, precision)**5412 * mpfr(0.37, precision)**2977 * mpfr(0.40, precision)**3588)

print(result)

Output:

1 'mpfr' number of precision  120   bits 
[1] 0.0012191160601483692718001967190171336975

Upvotes: 3

Related Questions