For mathematical calculations, the most common ones are actually the operations we use various operators, such as + addition and-subtraction. Of course, PHP also provides us with some operation functions that can easily perform other mathematical operations. These functions belong to Math extensions. This extension is included in the PHP source code by default, no additional installation is required, and no special parameters are required during compilation. It can be used directly.

Common mathematical functions

First, let's take a look at the more common mathematical functions.

var_dump(abs(-12)); // int(12)
var_dump(abs("-12.22")); // float(12.22)

var_dump(ceil(2)); // float(2)
var_dump(ceil(2.1)); // float(3)
var_dump(ceil(2.9)); // float(3)
var_dump(ceil(-2.9)); // float(-2)

var_dump(floor(2)); // float(2)
var_dump(floor(2.1)); // float(2)
var_dump(floor(2.9)); // float(2)
var_dump(floor(-2.9)); // float(-3)

abs() is the absolute value of the obtained data. ceil() is used to discard the decimal places and return an upward integer. For example, the result returned after using ceil() in 2.1 in our test code is 3. The result returned by -2.9 is 2. In fact, what is returned is an integer that discards the decimal and is not less than the given data.

The effect of floor() and ceil() are reversed, and it returns an integer less than the given data after discarding the floating point number.

var_dump(fmod(5.7, 1.3)); // float(0.5)
var_dump(fmod(6, 3));  // float(0)

var_dump(pow(2,5)); // int(32)
var_dump(sqrt(9)); // float(3)
var_dump(sqrt(10)); // float(3.1622776601684)

What fmod() returns is the remainder after taking the modulus. It has decimals. If you directly use% to take the modulus, it will only return an integer. You can try the 5.7% 1.3 result.

pow() is also a more commonly used power function, and the second parameter is the power of the first parameter. sqrt() is a quadratic root function, and the result of square root of 9 is 3.

In addition to sqrt(), there are several square root constants defined by the system for us.

var_dump(M_SQRT2); // sqrt(2) float(1.4142135623731)
var_dump(M_SQRT3); // sqrt(3) float(1.7320508075689)
var_dump(M_SQRT1_2); // 1/sqrt(2) float(0.70710678118655)

Their corresponding effect is actually the effect of calling the sqrt() function as stated in the comment. For example, M_SQRT2 is equivalent to the square root of 2 sqrt(2).

var_dump(max(10, 20, 39, 25)); // int(39)
var_dump(min(5, 3, 1, 9, 8)); // int(1)

var_dump(max([10, 20, 39, 25])); // int(39)
var_dump(min([5, 3, 1, 9, 8])); // int(1)

The max() function is used to return the largest number in the specified parameter, and the min() function is used to return the smallest number in the specified parameter. The parameters of these two functions are not fixed length, that is, you can pass as many parameters as you like. It can also directly receive an array as a parameter and return the largest element in the array. These two functions can cooperate to specify the maximum and minimum range of a variable. For example, our pagination:

max(1, min(100, $page));

It means that the current page passed over can only be in the range of 1-100. If it exceeds 100, it returns 100. If it is less than 1, it returns 1. It may be the first time that students who are exposed to these two functions will feel dizzy when they see this, so try to figure it out carefully!

var_dump(is_finite(M_PI)); // bool(true)
var_dump(is_infinite(M_PI)); // bool(false)
var_dump(is_finite(M_EULER)); // bool(true)

is_finite() and is_infinite() are used to determine whether the data is irrational. When is_finite() is used, if the data is irrational, it will return true. On the other hand, is_infinite() returns false for irrational numbers and true for rational numbers.

Pi related

In the above, we saw a constant M_PI. It represents 3.14... the value of the pi.

var_dump(M_PI); // float(3.1415926535898)
var_dump(pi()); // float(3.1415926535898)

As you can see, if you print directly, M_PI is only accurate to 13 digits after the decimal point, but if judged by is_finite(), it returns an irrational number, that is, an infinite number without recurring decimals. In addition, through the pi() function, the value of pi can also be obtained. In addition, there are a bunch of constants related to pie.

var_dump(M_PI_2); // pi()/2 float(1.5707963267949)
var_dump(M_PI_4); // pi()/4 float(0.78539816339745)
var_dump(M_1_PI); // 1/pi() float(0.31830988618379)
var_dump(M_2_PI); // 2/pi() float(0.63661977236758)
var_dump(M_SQRTPI); // sqrt(pi()) float(1.7724538509055)
var_dump(M_2_SQRTPI); // 2/sqrt(pi) float(1.1283791670955)
var_dump(M_LNPI); // log_e(pi()) float(1.1447298858494)

The meanings they represent have also been explained in the notes. For example, M_PI_2 means the result after dividing by 2.

logarithm

Although we are familiar with some commonly used logarithms, some logarithmic hands that are not commonly used or generated after calculation are very troublesome. Don't worry, PHP has also prepared logarithmic calculation functions for us.

var_dump(log(32)); // float(3.4657359027997)
var_dump(log(32, 2)); // 5

By default, the log() function is calculated based on the logarithm of the base 10. We can directly specify the second parameter as the base.

var_dump(log10(1000)); // float(3)

var_dump(log1p(31)); // float(3.4657359027997)

var_dump(exp(12)); // float(162753.791419)

log10() is obviously a logarithmic operation directly to the base 10. And log1p() returns the result of log(1+number), that is, 1 is added to the logarithm by default. The exp() function is to calculate the exponent of e, and the value calculated in the test code is e 12 .

var_dump(M_E); // e float(2.718281828459)
var_dump(M_LOG2E); // log_2 e float(1.442695040889)
var_dump(M_LOG10E); // log_10 e float(0.43429448190325)
var_dump(M_LN2); // log_e 2 float(0.69314718055995)
var_dump(M_LN10); // log_e 10 float(2.302585092994)

Similarly, logarithms also have many constants, and the specific explanations are also in the comments, so you can read them for yourself.

random number

The function of random numbers is probably the most commonly used in Math extensions.

var_dump(getrandmax()); // int(2147483647)

The getrandmax() function is used to return the maximum value that a random number can generate. Combine the following rand() function to see what this function does.

var_dump(rand()); 
var_dump(rand(5, 15));

If we don't specify the parameters of the rand() function, that is, if we don't specify its range, then the value generated by the rand() function is any random number in the range from 0 to getrandmax(). If we specify a range for the rand() function, only random numbers within the specified range will be generated.

var_dump(mt_getrandmax()); // int(2147483647)
var_dump(mt_rand()); 
var_dump(mt_rand(5, 15));

The three random number-related functions at the beginning of mt_ are no different from ordinary rand() in use. But now it is more recommended to use mt_rand() to generate random numbers. The average speed of it generating random numbers is four times faster than rand(), which is stated in the official documentation, and mt_rand() is also informally used to replace the rand() function in the documentation. Anyway, since the official documentation says so, let's use mt_rand() as much as possible.

In addition, there is no need to prepare random number seeds in advance to generate random numbers, that is, there is no need to use the two functions srand() or mt_srand(). You may see them in some frameworks, so I won’t demonstrate them here.

Trigonometric function

Trigonometric function is estimated to be a nightmare in everyone's middle school period. In fact, in program development, except for certain areas, there are really not many opportunities to use them. Just like I have never used it before, so here is a simple demonstration.

var_dump(hypot(3,4)); // float(5)
var_dump(hypot(5,12)); // float(13)

The first is a function hypot() that calculates the hypotenuse of a triangle. We used the two most classic Pythagorean numbers in the test here. I believe this result will bring back good memories of everyone in middle school.

var_dump(sin(M_PI_2)); // float(1)
var_dump(cos(M_PI_2)); // float(6.1232339957368E-17)
var_dump(tan(M_PI_2)); // float(1.6331239353195E+16)

var_dump(sin(deg2rad(90))); // float(1)

var_dump(asin(sin(M_PI_2))); // float(1.5707963267949)
var_dump(acos(cos(M_PI_2))); // float(1.5707963267949)
var_dump(atan(tan(M_PI_2))); // float(1.5707963267949)

var_dump(sinh(sin(M_PI_2))); // float(1.1752011936438)
var_dump(cosh(cos(M_PI_2))); // float(1)
var_dump(tanh(tan(M_PI_2))); //float(1)

var_dump(asinh(sin(M_PI_2))); // float(0.88137358701954)
var_dump(acosh(cos(M_PI_2))); // float(NAN)
var_dump(atanh(tan(M_PI_2))); // float(NAN)

This blockbuster film doesn't need to be explained any more, it's tears if you talk about it too much. One of the special ones is that we can see that there is a deg2rad() method, which is a function used to convert angles into radians. The ones with a in the front are the inverse functions corresponding to the trigonometric functions, the ones with h behind are the hyperbolic functions corresponding to the trigonometric functions, and the ones with a and h are the inverse hyperbolic functions.

In the last two pieces of test code, our data appeared NAN. I believe that many students will have seen this type intentionally or unintentionally during the development process. NAN is a very special type, which is intended to represent the concept of non-number. But it doesn't belong to any scalar type, and two NANs are not equal, and json_encode() cannot have this type of NAN. I believe that friends who have done financial or statistical analysis related systems must have a deep understanding of this NAN.

var_dump(atanh(tan(M_PI_2)) == atanh(tan(M_PI_2))); // bool(false)
var_dump(atanh(tan(M_PI_2)) === atanh(tan(M_PI_2))); // bool(false)

var_dump(NAN == NAN); // bool(false)
var_dump(NAN === NAN); // bool(false)

$v = json_encode([
    'test'=>NAN
]);
echo $v, PHP_EOL; // 
echo json_last_error_msg(); // Inf and NaN cannot be JSON encodedbool(true)

Is it a weird data type? It is necessary to determine whether a calculation result is of NAN type. You can only use the is_nan() function.

var_dump(is_nan(atanh(tan(M_PI_2)))); // bool(true)
var_dump(is_nan(NAN)); // bool(true)

Base conversion

Finally, there is the calculation of the hexadecimal conversion. To be honest, during the interview, someone asked me how to convert between binary and decimal. In fact, it was expected that I would write the conversion code by hand. But buddies wrote directly the functions of these hexadecimal conversions, and the interviewer had a black line at the time...

var_dump(bindec("11")); // int(3)
var_dump(bindec("110011")); // int(51)

var_dump(hexdec("FF")); // int(255)
var_dump(hexdec("A37334")); // int(10711860)

var_dump(octdec('77')); // int(63)

bindec() converts binary to decimal, hexdec() converts hexadecimal to decimal, and octdec() converts octal to decimal.

var_dump(decbin(51)); // string(6) "110011"
var_dump(dechex(255)); // string(2) "ff"
var_dump(decoct(63)); // string(2) "77"

Change the position of the word, put dec to the front, and it becomes the function of converting decimal to corresponding hexadecimal. These are relatively simple, and finally, there is a function that can perform arbitrary base conversion.

var_dump(base_convert("A37334", 16, 10)); // string(8) "10711860"
var_dump(base_convert("A37334", 16, 2)); // string(24) "101000110111001100110100"

base_convert() means to convert the content of the first parameter from the base of the second parameter to the base of the third parameter. For example, in this test code, we convert A37334 from hexadecimal to decimal and binary.

Summarize

Today's content is very rich, there are actually some functions related to mathematical calculations, but they are not too commonly used, so I won't write more here. Mathematics is the foundation of computer and the foundation of all majors in science and engineering. The functions provided for us in computer programming language should be mastered flexibly, especially in certain interview scenarios.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202012/source/9. Introduction to the application of math-related functions in PHP. php

Reference documents:

https://www.php.net/manual/zh/book.math.php

Searchable on their respective media platforms [Hardcore Project Manager]


硬核项目经理
90 声望18 粉丝