用接近0和1的概率进行计算时,如何提高R的精度? [英] How can I increase precision in R when calculating with probabilities close to 0 and 1?

查看:116
本文介绍了用接近0和1的概率进行计算时,如何提高R的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,代表[0,1]区间中的概率的变量总和为0,但应为>0.该问题肯定与浮点表示R中的精度有关,但是我无法确定问题出在哪里.

I have the problem that a sum of variables representing probabilities in the [0,1] interval sum to 0 but should be >0. The problem is surely related to floating point representation and precision in R, but I cannot pin down where it goes wrong.

options(digits = 22)
p1 = 0.8
p2 = 0.9999999999999998

p11 = p1 * p2
p10 = p1 - p11
p01 = p2 - p11
p00 = 1 - p11 - p10 - p01

p11, p10, p01均为numeric. p00也是numeric

> p00
[1] 0

p00 == 0在我的机器上是TRUE.但是,它不应为零,因为可以证明p00在数学上是>0.

and p00 == 0 is TRUE on my machine. However it should not be zero as it can be shown that p00 is >0 mathematically.

此问题似乎与p01很小的事实有关.但是p01>0TRUE仍适用于我的机器.为什么在p00中取最后的总和会出错?

This problem seems to be related to the fact that p01 is small. However p01>0 is TRUE still applies on my machine. Why does it go wrong when taking the final sum in p00?

是否存在解决此问题的数字技巧,即获得p00的精确表示形式?再次注意,p[0,1]中的概率.我考虑过使用logexp转换,但是没有取得一致的成功.

Is there a numerical trick to solve this problem, i.e. get an exact representation of p00? Note again p are probabilities in [0,1]. I considered using log and exp transformations but without consistent success.

推荐答案

R本身只能处理64位浮点数,Rmpfr程序包可以处理任意精度的浮点数:

R itself can only deal with 64 bit floating point numbers, the Rmpfr package can deal with arbitrary precision floating point numbers:

library(Rmpfr)

> p1 = mpfr("0.8", 128)
> p2 = mpfr("0.9999999999999998", 128)

> p11 = p1 * p2
> p10 = p1 - p11
> p01 = p2 - p11
> p00 = 1 - p11 - p10 - p01

> p00
1 'mpfr' number of precision  128   bits 
[1] 4.00000000000000000000000461461738779728e-17

使用st定义mpfr

这篇关于用接近0和1的概率进行计算时,如何提高R的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆