如何在R中处理大量数字? [英] How to work with large numbers in R?

查看:105
本文介绍了如何在R中处理大量数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改R的计算精度.例如,我想用x = c(-2.5e+59, -5.6e+60)计算x^6.为了计算它,我应该更改R的精度,否则结果为Inf,我不知道该怎么做.

解决方案

正如Livius在他的评论中指出的那样,这是R(实际上是大多数编程语言)的问题,即数字如何用二进制表示./p>

要使用非常大/小的浮点数,可以使用Rmpfr库:

install.packages("Rmpfr")
library("Rmpfr")
x <- c(-2.5e+59, -5.6e+60)
y <- mpfr(x, 6)  # the second number is how many precision **bits** you want - NB: not decimal places!
y^6
# 2 'mpfr' numbers of precision  6   bits 
# [1] 2.50e356 3.14e364

要使用甚至大于R可以处理的数字(例如exp(1800)),您可以使用"Brobdingnag"包:

install.packages("Brobdingnag")
library("Brobdingnag")

## An example of a single number too large for R: 
10^1000.7
# [1] Inf

## Now using the Brobdingnag package:
10^as.brob(1000.7)
# [1] +exp(2304.2)

I would like to change the precision in a calculation of R. For example I would like to calculate x^6 with x = c(-2.5e+59, -5.6e+60). In order to calculate it I should change the precision in R, otherwise the result is Inf, and I don't know how to do it.

解决方案

As Livius points out in his comment, this is an issue with R (and in fact, most programming language), with how numbers are represented in binary.

To work with extremely large/small floating point numbers, you can use the Rmpfr library:

install.packages("Rmpfr")
library("Rmpfr")
x <- c(-2.5e+59, -5.6e+60)
y <- mpfr(x, 6)  # the second number is how many precision **bits** you want - NB: not decimal places!
y^6
# 2 'mpfr' numbers of precision  6   bits 
# [1] 2.50e356 3.14e364

To work with numbers that are even larger than R can handle (e.g. exp(1800)) you can use the "Brobdingnag" package:

install.packages("Brobdingnag")
library("Brobdingnag")

## An example of a single number too large for R: 
10^1000.7
# [1] Inf

## Now using the Brobdingnag package:
10^as.brob(1000.7)
# [1] +exp(2304.2)

这篇关于如何在R中处理大量数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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