Basic mathematics will be used extensively in the programming process. When we write code, we often need to compare, add, multiply, subtract, and divide different values.
Sometimes the math required in a program can be more involved. You may need to use logarithmic, trigonometric, or exponential functions. In this tutorial, I will discuss how to use each function in PHP with examples.
This tutorial will introduce you to the built-in mathematical functions in PHP for performing trigonometric, exponential, and logarithmic calculations. We will also look at rounding and generating random numbers.
You can calculate the sine, cosine, and tangent of different angles given in radians using sin($angle)
, cos($angle)
, and tan ($angle)
. They both return a float
value, with the angle measurement passed to them in radians.
This means that when you simply calculate tan(45)
, you will not get 1 as output because you will actually be calculating the tangent value at 45 radians, which is approximately 2,578 degrees. Fortunately, PHP has two very useful functions for converting radians to degrees and vice versa. These functions are rad2deg()
and deg2rad()
. So if you really want to calculate the tangent of 45 degrees, you have to write tan(deg2rad(45))
.
It is worth noting that there is no direct PHP function to calculate the value of cosec()
, sec()
or cot()
. However, these The values are just the reciprocals of sin()
, cos()
and tan()
, so you can still calculate their values indirectly.
You can also do the inverse operation and calculate the angle of a triangle with a specific value. These functions are called asin()
, acos()
, and atan()
. One thing you have to remember is that the values of sin and cos cannot be outside the range -1 to 1 for any angle. This means that asin()
and acos()
can only accept values in the range -1 to 1 as valid arguments. Values outside this range will give you NaN.
Trigonometry has many applications, such as determining the trajectory of a projectile or the height and distance of different objects, so if you are writing code that simulates these situations, having access to these functions will definitely be helpful.
These functions are also useful when you want to draw different elements using radial and angular values. Suppose you want to draw a circle pattern at even distances around a larger circle. If you've read the PHP GD shapes tutorial on Envato Tuts, you might remember that drawing any shape requires you to pass coordinates in the form of x,y coordinates, but it's easier to draw circular patterns using polar coordinates.
Using these trigonometric functions in this case will help you to draw the desired graph by converting polar coordinates to Cartesian form using sin()
and cos()
. Here is an example:
<?php $image = imagecreatetruecolor(800, 600); $bg = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bg); $radius = 80; for($i = 0; $i < 12; $i++) { $col_ellipse = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200)); imagefilledellipse($image, 175 + 125*cos(deg2rad($i*30)), 175 + 125*sin(deg2rad($i*30)), 3*$radius/4, 3*$radius/4, $col_ellipse); imageellipse($image, 175 + 125*cos(deg2rad($i*30)), 175 + 125*sin(deg2rad($i*30)), 3.5*$radius/4, 3.5*$radius/4, $col_ellipse); $col_ellipse = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200)); imagefilledellipse($image, 575 + 150*cos(deg2rad($i*30)), 375 + 150*sin(deg2rad($i*30)), 3*$radius/4, 3*$radius/4, $col_ellipse); imageellipse($image, 575 + 150*cos(deg2rad($i*30)), 375 + 150*sin(deg2rad($i*30)), 3.5*$radius/4, 3.5*$radius/4, $col_ellipse); } $col_ellipse = imagecolorallocate($image, 255, 255, 255); imagefilledellipse($image, 175, 175, 275, 275, $col_ellipse); ?>
The image below shows the final result of the above PHP code.
PHP also has some exponential and logarithmic functions. exp($value)
The function will return the constant e raised to the power of float $value
. Likewise, you can use the log($arg, $base)
function to calculate the logarithm of a given number to any base. If $base
is omitted, the natural base e is used to calculate the logarithm. If you want to calculate the base 10 logarithm of a number, you can simply use the function log10($arg)
.
Another function you may find useful is pow($base, $exp)
, which returns $exp
of $base
. Some people You may prefer to use the **
operator. The expression $a**$b
will give the same result as pow($a, $b)
. However, in some cases, using $a**$b
may give incorrect results. For example, -1**0.5
will give you -1, which is incorrect. Evaluating the same expression using pow(-1, 0.5)
will give the correct value NaN.
<?php echo log(1000, M_E); // 6.9077552789821 echo log(1000); // 6.9077552789821 echo log(1000, 10); // 3 echo log10(1000); // 3 echo pow(121, -121); // 9.6154627930786E-253 echo pow(121, 121); // 1.0399915443694E+252 echo pow(121, 1331); // INF ?>
还有许多其他重要的数学函数。您可以使用 ceil(float $value)
函数将分数或小数四舍五入到最接近的整数。这会将 2.1 和 2.9 转换为 3。同样,您可以使用 floor(float $value)
函数将分数或小数舍入为最接近的整数。它将把 2.1 和 2.9 都更改为 2。
这些函数有助于轻松地对不同计算的结果进行舍入。假设您需要知道大厅可容纳多少人(根据其面积)。除法后的最终答案很可能是一个十进制数,但你不能将人分成分数,因此正确的答案将是计算值的下限值。
您经常需要将数字向上或向下舍入为最接近的整数。例如,您可能想要将 2.1 更改为 2,但将 2.9 更改为 3。这可以使用 round($value, $ precision, $mode)
函数轻松完成。 $ precision
参数确定要舍入的小数位数。默认值 0 将仅返回整数。第三个 $mode
参数用于确定如果要舍入的数字恰好位于中间会发生什么。您可以使用它来指定是否应将 3.5 更改为 3 或 4。
PHP 还有两个函数 min($values)
和 max($values)
来帮助您确定集合或数组中的最低和最高值数字。这些函数可以接受不同类型的参数,例如两个数组和一个字符串。您应该查看文档以了解如何比较它们。
<?php $hall_width = 120; $hall_length = 180; $per_person_area = 35; $hall_capacity = floor($hall_length*$hall_length/$per_person_area); // Output: The hall can only accommodate 925 people. echo 'The hall can only accommodate '.$hall_capacity.' people.'; $water_tank_volume = 548733; $bucket_volume = 305; $buckets_needed = ceil($water_tank_volume/$bucket_volume); // Output: We will need 1800 buckets of water to completely fill the tank. echo 'We will need '.$buckets_needed.' buckets of water to completely fill the tank.'; $marks = [49, 58, 93, 12, 30]; // Output: Minimum and maximum obtained marks in the exam are 12 and 93 respectively. echo 'Minimum and maximum obtained marks in the exam are '.min($marks).' and '.max($marks).' respectively.'; ?>
您还可以使用 intdiv($dividend, $divisor)
函数在 PHP 中执行整数除法。在这种情况下,除法后仅返回商的整数部分。同样,您还可以使用 fmod($dividend, $divisor)
函数获得两个参数相除后的余数或模数。返回值的大小始终小于 $divisor
的大小。
还有一些其他有用的函数,例如 is_nan($value)
、is_finite($value)
和 is_infinite($val)
可用于确定该值是否为数字,如果是数字,则确定它是有限还是无限。请记住,PHP 认为任何太大而无法放入浮点数的值都是无限的。因此 is_finite()
将返回 true
100 阶乘,但 false
1000 阶乘。
事实证明,随机数在许多情况下都非常有用。您可以使用它们为您的应用程序生成“随机”数据或在游戏中生成敌人实例等。记住这一点非常重要,我们在本节中讨论的函数都不会生成加密安全的随机数。这些功能仅适用于安全性不成问题的情况,例如向重复访问者显示随机问候文本或生成随机统计数据。
函数 rand($min, $max)
和 mt_rand($min, $max)
可以生成给定值之间的正随机整数,包括 $min
和 $max
值。当不带任何参数调用函数时,它们会生成 0 到 getrandmax()
之间的随机数。您可以 echo
getrandmax()
的值来查看这些函数在您的平台上可以生成的最大可能随机数。
函数 mt_rand()
比 rand()
快 4 倍,如果 $max
小于 $min
。从 PHP 7.1.0 开始,rand()
实际上已成为 mt_rand()
的别名。唯一的区别是,如果 $max
小于 $min
,则 rand()
仍然不会给出错误,以保持向后兼容性。
这是一个循环,用于生成 0 到 100 之间的随机值一百万次。正如您所看到的,值 0、50 和 100 大约生成了 10,000 次,并且有轻微波动。
<?php $rand_values = []; $sum = 0; $count = 1000000; for($i = 0; $i < $count; $i++) { $rand_values[$i] = mt_rand(0, 100); $sum += $rand_values[$i]; } $count_frequency = array_count_values($rand_values); // Output: 100 was randomly generated 9969 times. echo '100 was randomly generated '.$count_frequency[100].' times.'; // Output: 50 was randomly generated: 9994 times. echo '50 was randomly generated: '.$count_frequency[50].' times.'; // Output: 0 was randomly generated: 10010 times. echo '0 was randomly generated: '.$count_frequency[0].' times.'; // Output: Average of random values: 49.97295 echo 'Average of random values: '.($sum/$count); ?>
这两个函数也有自己的种子函数,称为 srand()
和 mt_srand()
,为随机数生成器提供种子。您应该记住,您只在程序中调用 srand()
和 mt_srand()
一次。在每次调用 rand()
和 mt_rand()
之前调用它们每次都会给你相同的“随机”数字。
<?php srand(215); echo rand()."\n"; // 330544099 srand(215); echo rand()."\n"; // 330544099 srand(215); echo rand()."\n"; // 330544099 echo rand()."\n"; // 138190029 echo rand()."\n"; // 1051333090 echo rand()."\n"; // 1219572487 ?>
PHP 附带了许多内置函数,可以满足您所有的日常计算需求。您可以使用这些函数自己进行稍微复杂的计算,例如 GCD、LCM 和阶乘。
There are a few things you should keep in mind when using these functions. For example, the value returned by functions such as floor()
and ceil()
is an integer, but it is still a floating point number. Likewise, all trigonometric functions expect their angles to be in radians. If you pass them an angle value that you want to be treated as a measure of degrees, you will get incorrect results. Therefore, be sure to check the documentation for the return values and expected parameters of all these functions.
The above is the detailed content of Explore trigonometry, random number generation, and more using PHP's built-in math functions. For more information, please follow other related articles on the PHP Chinese website!