Math Functions in PHP

Lecture



In this lesson I will introduce readers to the mathematical functions that are available in PHP. More precisely, in the examples only the most frequent ones will be used, since the complete list is easiest to find on the official website, along with detailed descriptions.
The purpose of this lesson is not to provide a complete list of these functions, but to give some examples of their use.

Mathematical functions are intended for work of variables of numerical types. This means that the operands will be variables of type int and float .
I will divide these functions into several types:

0. Common functions
1. Trigonometric functions
2. Inverse trigonometric functions
3. Logarithmic functions
4. Power functions
5. Functions of base transformation
6. The rest (which are difficult to classify)


General functions

I referred to common functions as functions:
abs
floor
ceil
max
min
round
rand
sqrt
I will describe them in more detail.

abs
Syntax:
number abs (mixed number)
The function calculates the modulus of a number. Let me remind you that | x | = x, if x> 0 or x = 0, and | x | = -x, if x <0.

floor
Syntax:
float floor (float value)
This function rounds the fraction down. But do not think that this is the "dropping" of the fractional part. Because, firstly, the result will still not be integer, but real. In addition, for negative numbers, the nearest smaller integer will be a fraction added to it.

ceil
Syntax:
float ceil (float value)
This function also rounds the argument to the nearest integer, but already to the nearest larger integer. The floor and ceil functions return a real result for one simple reason - the range of real numbers in PHP is greater than integers.

max
Syntax:
mixed max (number arg1, number arg2 [, number ...])
mixed max (array numbers)
This function has 2 syntax descriptions. It returns the maximum value among the arguments if they are passed in the form of a complete list (1st variant of the syntax), or the largest element of the array, in case the array was passed (2nd 2nd syntax). Curiously, the arguments can be of different types. Let's say

<?PHP
$test = max('строка', array(0, 1), 4, 7);
//вернется array(0, 1) - массив всегда будет считаться больше остального, хотя такое "сравнение" выглядит довольно глупо
?>

I can not imagine why this may be required, but nevertheless, in PHP it works that way.
Completely similar min function, it can even not be described. The difference is that the minimum is returned.

round
Syntax:
float round (float val [, int precision])
Rounds a real number according to arithmetic rules. You can specify the accuracy of rounding. In this case, it will be rounded to the specified number of fraction characters. This precision can be set to 0 (equivalent to calling a function without specifying a precision). In addition, you can specify a negative value of accuracy. The result is similar.

rand
Syntax:
int rand ([int min, int max])
Returns a random integer between min and max, inclusive. These parameters are optional. If not specified, a random number in the range from 0 to the constant RAND_MAX will be returned.
On Windows operating systems, RAND_MAX is only 32767
If you need a random fractional number, you can use, for example, the following code:

<?PHP
//Генерируем случайное вещественное число в диапазоне $a..$b в предположении $a<$b
$iMaxRand=30000;//по сути, можно задавать и больше для большей точности
$iRand=rand(1, $iMaxRand);
$fRand=$a+($b-$a)*$iRand/$iMaxRand;
?>

sqrt
Syntax:
float sqrt (float arg)
The function calculates the square root of the argument. Both the argument and the result are real.


Trigonometric and inverse trigonometric functions

To the trigonometric functions I attributed the functions:
acos
acosh
asin
asinh
atan2
atan
atanh
cos
cosh
sin
sinh
tan
tanh

All these functions take as an argument parameters of type float, and return a value of the same type. For the reason that their description requires only knowledge of what exactly each of them does, I will not give all the descriptions here. (And the purpose of these functions is known from geometry and algebra).

acos
Syntax:
float acos (float arg)
Calculates the arc cosine of a number. If the argument is invalid (that is, | arg |> 1), returns NAN.


Logarithmic functions

To logarithmic functions, I attributed the functions:
log10
log1p
log

These functions also do not require a separate description. Separately, I will only say about the function log1p. The fact is that, by virtue of the peculiarity of the logarithm, for values ​​of an argument close to 1, it strongly tends to zero. This can be a nuisance to thin calculations. This function calculates the value in a more accurate way.
Among other things, I will give an example of a useful function that calculates the logarithm on an arbitrary basis:

<?PHP
function Log($base, $arg)
{
if($base==1||$base<=0)
{
return null;
}
if($arg<=0)
{
return null;
}
return log($arg)/log($base);
}
?>

Yes, by the way, the question for readers - I called the Log function - won't it cause a conflict with the name of the already existing log function?


Power functions

Let us turn to the power functions:

exp
expm1
pow

Similar to logarithms, we should separately pay attention only to expm1, which returns exactly the calculated power of the argument close to 0.


Calculus base conversion functions

In php there is a special series of functions that work with the conversion of number systems. If we take into account that bin is a binary system, oct is octal, dec is decimal, and hex is hexadecimal, the purpose of many of them becomes intuitive:

base_convert
bindec
decbin
dechex
decoct
hexdec
octdec

Of interest is the base_convert function:

base_convert
Syntax:
string base_convert (string number, int frombase, int tobase)
Returns a string containing the number number represented with the base tobase. The base in which the number is given is specified in frombase. Both frombase and tobase must be in the range from 2 to 36 inclusive. Why such a restriction? Yes, because the numbers, more than 10, are written using the symbols of the Latin alphabet. That is, from a to z. Together with the first 9 bases, 35 possible values ​​will be released.


Unclassified functions

In conclusion, I will give a number of useful, not classified by me separately, functions:

is_finite
is_infinite
is_nan

is_finite
Syntax:
bool is_finite (float val)
This function determines whether a number is finite in terms of a range of floating point numbers. This range is taken based on the current platform.

is_finite
Syntax:
bool is_infinite (float val)
This function determines whether a number is infinite in terms of a range of floating point numbers. At the same time, of course, the capabilities of the platform are taken into account, but, let's say, the result of log (0) will not be such on any platform (you can think why)

is_nan
Syntax:
bool is_nan (float val)
Indicates whether the argument is a real number. From the point of view of algebra, the category of non-real numbers will fall as non-numbers at all (like arc cosine from two), as well as complex numbers (like the square root of -1). In both cases, the function will return false.

At the end of the lesson, as usual, I will give a number of questions.

1. What does the is_nan function return if the argument passed to it is a transcendental number from the algebra point of view?

2. Suppose we have 1–9 ordinary numbers, az numbers from 10 to 35, and AZ numbers from 36 to 62. Write a function that converts a number from one number system to another (like base_convert), but with such notation (i.e. the argument takes a value from 2 to 62)

3. What is the difference between is_nan and is_finite? Give examples when their values ​​from the same argument are different.

0. Returns true if it is assumed that such numbers are valid. If the reader knows the subject matter of the question (or was not too lazy to look into Wikipedia), then he knows that the transcendental numbers are ordinary real numbers. But they are the roots of a polynomial with irrational coefficients. The only thing is that their representation in the flop type of php will make them no longer transcendental at all. So, from the point of view of float, the is_nan function will return true. If we assume that transcendental numbers cannot be written as a float representation, then it will not return anything at all (there will be no argument)
one.
PHP:
  1. <? PHP
  2. class Converter
  3. {
  4. protected $ cipherSet;
  5. protected $ rgCiphers;
  6. protected $ inputSet;
  7. protected $ outputSet;
  8. protected $ fromBase;
  9. protected $ toBase;
  10. protected $ iErrorCode;
  11. protected $ sErrorMessage;
  12. / * Submit only full cipher set * /
  13. function __construct ($ strSet)
  14. {
  15. $ this-> cipherSet = $ strSet;
  16. $ this-> iErrorCode = 0;
  17. $ this-> sErrorMessage = "";
  18. }
  19. / * multiplication with non-decimal base * /
  20. protected function baseArithmeticMult ($ num)
  21. {
  22. $ currentResultLen = count ($ this-> rgCiphers);
  23. if ($ currentResultLen == 0)
  24. {
  25. return;
  26. }
  27. $ rgMods = array ();
  28. $ currentPos = 0;
  29. $ div = 0;
  30. do
  31. {
  32. $ divided = 0;
  33. if ($ currentResultLen> $ currentPos)
  34. {
  35. $ divided = $ this-> rgCiphers [$ currentPos] * $ num;
  36. }
  37. $ divided + = $ div;
  38. $ rgMods [$ currentPos] = $ divided% $ this-> toBase;
  39. $ div = (int) ($ divided / $ this-> toBase);
  40. $ currentPos ++;
  41. }
  42. while ($ currentResultLen> $ currentPos || $ div! = 0);
  43. $ this-> rgCiphers = $ rgMods;
  44. }
  45. / * addition with non-decimal base * /
  46. protected function baseArithmeticPlus ($ num)
  47. {
  48. $ currentPos = 0;
  49. $ divided = $ num;
  50. do
  51. {
  52. $ divided + = (int) ($ this-> rgCiphers [$ currentPos]);
  53. $ this-> rgCiphers [$ currentPos] = $ divided% $ this-> toBase;
  54. $ divided = (int) ($ divided / $ this-> toBase);
  55. $ currentPos ++;
  56. }
  57. while ($ buf> 0);
  58. }
  59. / * error's getters * /
  60. public function getErrorCode ()
  61. {
  62. return $ this-> iErrorCode;
  63. }
  64. public function getErrorMessage ()
  65. {
  66. return $ this-> sErrorMessage;
  67. }
  68. / * main function * /
  69. public function baseConvert ($ num, $ fromBase = 0, $ toBase = 0)
  70. {
  71. $ num = (string) ($ num);
  72. $ totalCiphers = strlen ($ num);
  73. $ this-> inputSet = substr ($ this-> cipherSet, 0, $ fromBase);
  74. $ this-> outputSet = substr ($ this-> cipherSet, 0, $ toBase);
  75. $ this-> toBase = $ toBase;
  76. $ this-> rgCiphers = array ();
  77. for ($ currentPos = 0; $ currentPos <$ totalCiphers; $ currentPos ++)
  78. {
  79. $ currentCipher = $ num [$ currentPos];
  80. $ cipherSign = substr_count ($ this-> inputSet, $ currentCipher);
  81. if ($ cipherSign == 0)
  82. {
  83. $ this-> iErrorCode = 255;
  84. $ this-> sErrorMessage = "Cipher '". $ currentCipher. "' was not found in cipher set:". $ this-> inputSet;
  85. return null;
  86. }
  87. elseif ($ cipherSign> 1)
  88. {
  89. $ this-> iErrorCode = 255;
  90. $ this-> sErrorMessage = "Cipher '". $ currentCipher. "' was found more than once in cipher set:". $ this-> inputSet;
  91. return null;
  92. }
  93. if ($ currentPos! = 0)
  94. {
  95. $ this-> baseArithmeticMult ($ fromBase);
  96. }
  97. $ this-> baseArithmeticPlus (strpos ($ this-> inputSet, $ currentCipher));
  98. }
  99. $ convertedNum = ";
  100. $ totalCiphers = count ($ this-> rgCiphers);
  101. for ($ currentPos = 0; $ currentPos <$ totalCiphers; $ currentPos ++)
  102. {
  103. $ convertedNum = $ this-> outputSet [$ this-> rgCiphers [$ currentPos]]. $ convertedNum;
  104. }
  105. return $ convertedNum;
  106. }
  107. }
  108. ?>


2. Some examples:
is_nan (sqrt (-1)) and is_finite (sqrt (-1))
is_nan (acos (2)) and is_finite (acos (2))

 
created: 2016-01-26
updated: 2021-03-13
132469



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)