Explore trigonometry, random number generation, and more using PHP's built-in math functions

WBOY
Release: 2023-09-01 21:34:01
Original
982 people have browsed it

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.

Trigonometric functions in PHP

You can calculate the sine, cosine, and tangent of different angles given in radians usingsin($angle),cos($angle), andtan ($angle). They both return afloatvalue, with the angle measurement passed to them in radians.

This means that when you simply calculatetan(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 arerad2deg()anddeg2rad(). So if you really want to calculate the tangent of 45 degrees, you have to writetan(deg2rad(45)).

It is worth noting that there is no direct PHP function to calculate the value ofcosec(),sec()orcot(). However, these The values are just the reciprocals ofsin(),cos()andtan(), 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 calledasin(),acos(), andatan(). 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 thatasin()andacos()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 usingsin()andcos(). Here is an example:

Copy after login

The image below shows the final result of the above PHP code.

使用 PHP 的内置数学函数探索三角学、随机数生成等

Exponential and logarithmic functions

PHP also has some exponential and logarithmic functions.exp($value)The function will return the constanteraised to the power of float$value. Likewise, you can use thelog($arg, $base)function to calculate the logarithm of a given number to any base. If$baseis omitted, the natural baseeis used to calculate the logarithm. If you want to calculate the base 10 logarithm of a number, you can simply use the functionlog10($arg).

Another function you may find useful ispow($base, $exp), which returns$expof$base. Some people You may prefer to use the**operator. The expression$a**$bwill give the same result aspow($a, $b). However, in some cases, using$a**$bmay give incorrect results. For example,-1**0.5will give you-1, which is incorrect. Evaluating the same expression usingpow(-1, 0.5)will give the correct value NaN.

Copy after login

其他有用的数学函数

四舍五入数字

还有许多其他重要的数学函数。您可以使用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)来帮助您确定集合或数组中的最低和最高值数字。这些函数可以接受不同类型的参数,例如两个数组和一个字符串。您应该查看文档以了解如何比较它们。

Copy after login

整数除法

您还可以使用intdiv($dividend, $divisor)函数在 PHP 中执行整数除法。在这种情况下,除法后仅返回商的整数部分。同样,您还可以使用fmod($dividend, $divisor)函数获得两个参数相除后的余数或模数。返回值的大小始终小于$divisor的大小。

还有一些其他有用的函数,例如is_nan($value)is_finite($value)is_infinite($val)可用于确定该值是否为数字,如果是数字,则确定它是有限还是无限。请记住,PHP 认为任何太大而无法放入浮点数的值都是无限的。因此is_finite()将返回true100 阶乘,但false1000 阶乘。

在 PHP 中生成随机数

事实证明,随机数在许多情况下都非常有用。您可以使用它们为您的应用程序生成“随机”数据或在游戏中生成敌人实例等。记住这一点非常重要,我们在本节中讨论的函数都不会生成加密安全的随机数。这些功能仅适用于安全性不成问题的情况,例如向重复访问者显示随机问候文本或生成随机统计数据。

函数rand($min, $max)mt_rand($min, $max)可以生成给定值之间的正随机整数,包括$min$max值。当不带任何参数调用函数时,它们会生成 0 到getrandmax()之间的随机数。您可以echogetrandmax()的值来查看这些函数在您的平台上可以生成的最大可能随机数。

函数mt_rand()rand()快 4 倍,如果$max小于$min。从 PHP 7.1.0 开始,rand()实际上已成为mt_rand()的别名。唯一的区别是,如果$max小于$min,则rand()仍然不会给出错误,以保持向后兼容性。

这是一个循环,用于生成 0 到 100 之间的随机值一百万次。正如您所看到的,值 0、50 和 100 大约生成了 10,000 次,并且有轻微波动。

Copy after login

这两个函数也有自己的种子函数,称为srand()mt_srand(),为随机数生成器提供种子。您应该记住,您只在程序中调用srand()mt_srand()一次。在每次调用rand()mt_rand()之前调用它们每次都会给你相同的“随机”数字。

Copy after login

最终想法

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 asfloor()andceil()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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!