[英]How to convert Perl bigrat to bignum?
I have a huge rational number, which I need to convert to a decimal number. 我有一个很大的有理数,需要将其转换为十进制数。 How can I do this? 我怎样才能做到这一点?
The rational was created like this: 有理是这样创建的:
my $t;
{
use bigrat;
$t = (3 ** 1000) / (2 ** 1000);
}
I need to get the result $t in decimal form (integer part -dot- a few decimal digits) 我需要以十进制形式获得结果$ t(整数部分-点-几个十进制数字)
How can I do that conversion? 我该如何进行转换?
bigrat
tries to do everything transparently by overloading operators so that you can work without being aware of the underlying objects being used. bigrat
尝试通过重载运算符来透明地完成所有操作,以便您可以在不知道所使用的基础对象的情况下进行工作。 But it can't always get everything right, and you need to use Math::BigRat
directly to get the necessary control over the format of the intermediate numbers. 但是它不能总是使所有事情都正确,并且您需要直接使用Math::BigRat
来获得对中间数字格式的必要控制。
This code does what you ask. 这段代码可以满足您的要求。 The parameter to as_float
says how many digits you want in the output. as_float
的参数表示要在输出中显示多少位数。 Since 3 1000 ÷ 2 1000 is greater than 1e176 you need something more than 176 to show the decimal point at all. 由于3 1000 ÷2 1000大于1e176,因此您需要大于176的值才能显示小数点。 A value of 200 shows the first 23 decimal places. 值200表示前23个小数位。
use strict;
use warnings;
use 5.010;
use Math::BigRat;
my $t = do {
my $num = Math::BigRat->new(3) ** 1000;
my $den = Math::BigRat->new(2) ** 1000;
$num / $den;
};
say $t->as_float(200);
output 输出
123384059690617347922743909948678005742186900514842808542522975184329422623652841193932245134021231941529455308114511924428000273557831297406949841351167568024301164105271903064.98735542425778400198655
That's the same as 那和
use Math::BigRat qw( );
my $t = (Math::BigRat->new(3) ** Math::BigRat->new(1000))
/ (Math::BigRat->new(2) ** Math::BigRat->new(1000));
Math::BigRat provides Math :: BigRat提供
->as_float()
to get a Math::BigFloat ->as_float()
获得Math :: BigFloat
->numify()
to get a regular floating point number scalar. ->numify()
以获取常规浮点数标量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.