The Wayback Machine - https://web.archive.org/web/20241001062034/https://www.geeksforgeeks.org/perl-useful-math-functions/
Open In App

Perl | Useful Math functions

Last Updated : 12 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Perl, sometimes there is a need to solve various expressions that contain some mathematical operations. These mathematical operations can be performed with the use of various inbuilt-functions. 

Perl




#!/usr/bin/perl
   
# Initialising some values for the
# parameter of the exp function
$A = 0;
$B = 1;
 
# Calling the exp function
$E = exp $A;
$F = exp $B;
  
# Getting the value of "e" raised to the
# power of the given parameter.
print "$E\n";
print "$F\n";
 
# Calculating square root using sqrt()
$square_root = sqrt(64);
   
# Printing the result
print "Squareroot of 64 is: $square_root";


Some useful functions for mathematical operations in Perl are listed below: 

.math-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .math-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .math-table td:nth-child(odd) { background-color: #c6ebd9; } .math-table th { border: 1px solid #5fb962; text-align: left; } .math-table td { border: 1px solid #5fb962; color: black; text-align:left !important; } 

Function Description
exp() Calculates “e” raised to the power of the real number taken as the parameter
hex() Converts the given hexadecimal number ( of base 16 ) into its equivalent decimal number ( of base 10 ).
srand() Helps rand() function to generate a constant value each time the program is run
sqrt() Used to calculate the square root of a number
oct() Converts the octal value passed to its respective decimal value
rand() Returns a random fractional number between 0 and the positive number value passed to it, or 1 if no value is specified
log() Returns the natural logarithm of value passed to it. Returns $_ if called without passing a value
int() Returns the integer part of given value. It returns $_ if no value provided
sin() Used to calculate sine of a VALUE or $_ if VALUE is omitted
cos() Used to calculate cosine of a VALUE or $_ if VALUE is omitted
atan2()

Used to calculate arctangent of Y/X in the range –

PI to PI.

abs() Returns the absolute value of its argument

Perl has several built-in math functions that can be useful for performing mathematical operations in your scripts. Here are a few examples:

Perl




#!/usr/bin/perl
# your code here
#!/usr/bin/perl
 
use strict;
use warnings;
 
my $num = -5;
print "Absolute value of $num is " . abs($num) . "\n";
 
my $sqrt_num = 25;
print "Square root of $sqrt_num is " . sqrt($sqrt_num) . "\n";
 
my $log_num = 2.718281828459045;
print "Natural logarithm of $log_num is " . log($log_num) . "\n";
 
my $exp_num = 2;
print "Exponential value of $exp_num is " . exp($exp_num) . "\n";
 
my $angle = 90;
my $rad = $angle * (3.14159265359/180);
print "Sine of $angle degrees is " . sin($rad) . "\n";
 
$angle = 60;
$rad = $angle * (3.14159265359/180);
print "Cosine of $angle degrees is " . cos($rad) . "\n";
 
print "Random number between 0 and 1: " . rand() . "\n";


Output

Absolute value of -5 is 5
Square root of 25 is 5
Natural logarithm of 2.71828182845905 is 1
Exponential value of 2 is 7.38905609893065
Sine of 90 degrees is 1
Cosine of 60 degrees is 0.49999999999994
Random number between 0 and 1: 0.791284491381706

Advantages of using Perl math functions:

  • Provides a wide range of built-in math functions for performing complex mathematical calculations.
  • Supports both basic and advanced math functions, including trigonometric, logarithmic, exponential, and statistical functions.
  • The math functions are included in the core Perl distribution, so they are available on most systems without the need for additional installation or configuration.
  • Perl math functions are optimized for speed and efficiency, making them a good choice for high-performance computing tasks.

Disadvantages of using Perl math functions:

  • Some of the math functions may produce inaccurate results due to the limited precision of floating-point arithmetic.
  • Perl is a high-level scripting language, so it may not be the best choice for applications that require low-level control over memory and hardware resources.
  • The large number of available math functions can make it difficult to select the right function for a given task.
  • If you need to perform very specialized or advanced mathematical calculations, you may need to use a different programming language or specialized math library.

Important points regarding using Perl math functions:

  • Make sure to use the appropriate math function for the task at hand.
  • Be aware of the limitations of floating-point arithmetic and the potential for rounding errors in some calculations.
  • Always test your math functions thoroughly to ensure that they are producing the correct results.

Some useful references for working with Perl math functions include:

  • “Perl Cookbook” by Tom Christiansen and Nathan Torkington
  • “Learning Perl” by Randal L. Schwartz, brian d foy, and Tom Phoenix
  • “Mastering Perl” by brian d foy
  • The Perl documentation, available online at https://perldoc.perl.org/


Similar Reads

Perl | Useful String functions
A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“). Perl provides various functions to manipulate the string like
3 min read
Perl | Useful Array functions
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Array in Perl provides various inbuilt functions to perform operations like adding and removing elements from
2 min read
Perl | Useful Hash functions
A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Perl provides various functions to perform operations on Hashes, such as to return values of the hash, to delete elements from a hash, etc. Example: #!/usr/bin/perl # Initializing hash %hash1 = ('Welcome' => 10, 'to' => 2
2 min read
Perl | Useful File-handling functions
Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. These operations can be performed by the use of various inbuilt file functions. Example: #!/usr/bin/perl # Opening a File in Read-only mode open(fh, "<",
2 min read
Perl | Useful String Operators
A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“). Operators are the foundation of any programming language, so
3 min read
Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Perl | Math::BigInt->digit() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. digit() method of Math::BigInt module is used to get nth digit of the given number counting from right. To get the digit from the left side we need to specify n as negative. Syntax: Math::BigInt->digit($n) Paramete
3 min read
Perl | Math::BigInt->bzero() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. bzero() method of Math::BigInt module is used to create a new object with value zero and if used on an existing object, it sets it to zero. Syntax: Math::BigInt->bzero() Parameter: No Parameter Returns: object with
1 min read
Perl | Math::BigInt->length() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. length() method of Math::BigInt module is used to get the length of the given number i.e the count of digits in the given number. Syntax: Math::BigInt->length() Parameter: None Returns: an integer value which repre
2 min read
Perl | Math::BigInt->config() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. config() method of Math::BigInt module is used to get the information about the configuration of the Perl module. Syntax: Math::BigInt->config() Parameter: None Returns: a hash containing the configuration, e.g.cla
1 min read
Perl | Math::BigInt->brsft() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.brsft() method of Math::BigInt module is used to right shift the given value by a base given as parameter. Syntax: Math::BigInt->brsft()Parameter: $y- number of times shifting is to be done $n- base of shiftingRetur
1 min read
Perl | Math::BigInt->from_oct() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.from_oct() method of Math::BigInt module is used to convert the octal number passed as input to its corresponding decimal number. Syntax: Math::BigInt->from_oct()Parameter: input octal number to be convertedReturns:
1 min read
Perl | Math::BigInt->from_hex() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.from_hex() method of Math::BigInt module is used to convert the hexadecimal number passed as input to its corresponding decimal number. Syntax: Math::BigInt->from_hex()Parameter: input hexadecimal number to be conve
1 min read
Perl | Math::BigInt->from_bin() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.from_bin() method of Math::BigInt module is used to convert the binary number passed as input to its corresponding decimal number. Syntax: Math::BigInt->from_bin()Parameter: input binary number to be convertedReturn
1 min read
Perl | Math::BigInt->bnan() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. bnan() method of Math::BigInt module is used to create a new object with value NAN and if used on an existing object, it converts it to NAN. Syntax: Math::BigInt->bnan() Parameter: No Parameter Returns: NAN(Not A N
1 min read
Perl | Math::BigInt->bone() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. bone() method of Math::BigInt module is used to create a new object with value one and if used on an existing object, it sets it to one. Syntax: Math::BigInt->bone() Parameter: plus or minus: to set the sign of one
2 min read
Perl | Math::BigInt->binf() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. binf() method of Math::BigInt module is used to create a new object with value infinity and if used on an existing object, it sets it to infinity. Syntax: Math::BigInt->binf() Parameter: plus or minus: to set the s
2 min read
Perl | Math::BigInt->bneg() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. bneg() method of Math::BigInt module is used to change the value of input to its negative value and does nothing for zero or NAN values Syntax: Math::BigInt->bneg() Parameter: No Parameter Returns: object with valu
1 min read
Perl | Math::BigInt->bfac() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. bfac() method of Math::BigInt module is used to calculate factorial of a number stored as BigInt object. Syntax: Math::BigInt->bfac() Parameter: None Returns: a normalised BigInt object whose value represents the f
2 min read
Perl | Math::BigInt->is_even() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. is_even() method of Math::BigInt module is used to check whether a number stored as BigInt object is even or not. Syntax: Math::BigInt->is_even() Parameter: None Returns: true if the number stored in BigInt object
2 min read
Perl | Math::BigInt->is_odd() method
Math::BigInt module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators. is_odd() method of Math::BigInt module is used to check whether a number stored as BigInt object is an odd number or not. Syntax: Math::BigInt->is_odd() Parameter: None Returns: true if the number stored in BigInt
3 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Perl | List Functions
A list in Perl is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol. List provides various pr
4 min read
Perl | File I/O Functions
File handling in Perl is used to read data from an external file or to write data into an external file. This is very useful as it provides a platform to permanently store and retrieve data from files. File Handle A FileHandle associates a name to an external file, that can be used until the end of the program or until the FileHandle is closed. In
4 min read
Perl - Difference between Functions and Subroutines
In Perl, when a code-script gets bigger in size i.e. contains hundreds of lines of code, it becomes difficult to manage such a code-script. To avoid this difficulty, Perl provides its users with the concept of Functions and subroutines. Functions and subroutines break up complex/large amounts of code into smaller more concise parts to make the prog
4 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read