Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the floating point precision in Perl?

Is there a way to set a Perl script's floating point precision (to 3 digits), without having to change it specifically for every variable?

Something similar to TCL's:

global tcl_precision
set tcl_precision 3
like image 442
Igor Avatar asked Dec 03 '09 09:12

Igor


People also ask

How do you set a precision of a float?

To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).

How do I limit decimal places in Perl?

The f format lets you specify a particular number of decimal places to round its argument to. Perl looks at the following digit, rounds up if it is 5 or greater, and rounds down otherwise. Three functions that may be useful if you want to round a floating-point value to an integral value are int , ceil , and floor .

How much is the precision of floating-point?

The precision of floating-point numbers is either single or double, based on the number of hexadecimal digits in the fraction. A small integer is a binary integer with a precision of 15 bits. The range of small integers is -32768 to +32767. A large integer is a binary integer with a precision of 31 bits.

Why is floating-point not exact?

Floating-point decimal values generally do not have an exact binary representation due to how the CPU represents floating point data. For this reason, you may experience a loss of precision, and some floating-point operations may produce unexpected results.


2 Answers

Use Math::BigFloat or bignum:

use Math::BigFloat;
Math::BigFloat->precision(-3);

my $x = Math::BigFloat->new(1.123566);
my $y = Math::BigFloat->new(3.333333);

Or with bignum instead do:

use bignum ( p => -3 );
my $x = 1.123566;
my $y = 3.333333;

Then in both cases:

say $x;       # => 1.124
say $y;       # => 3.333
say $x + $y;  # => 4.457
like image 157
draegtun Avatar answered Sep 20 '22 13:09

draegtun


There is no way to globally change this.

If it is just for display purposes then use sprintf("%.3f", $value);.

For mathematical purposes, use (int(($value * 1000.0) + 0.5) / 1000.0). This would work for positive numbers. You would need to change it to work with negative numbers though.

like image 44
Xetius Avatar answered Sep 17 '22 13:09

Xetius