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.
2. Some examples:
is_nan (sqrt (-1)) and is_finite (sqrt (-1))
is_nan (acos (2)) and is_finite (acos (2))
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)