Home Backend Development PHP Tutorial Functions and example analysis of PHP mathematical operation functions

Functions and example analysis of PHP mathematical operation functions

Jun 04, 2018 am 10:50 AM
php Case Analysis

This article mainly introduces PHP mathematical operation functions, summarizes and analyzes the functions, usage methods and precautions of common PHP mathematical operation functions. Friends in need can refer to the following

1. Commonly used Function description:

Abs: Get the absolute value.

Acos: Get the arc cosine value.

Asin: Get the arcsine value.

Atan: Get the arctangent value.

Atan2: Calculate the arc tangent of a two number.

base_convert: Convert the carry method of the number.

BinDec: Convert binary to decimal.

Ceil: Calculate the smallest integer greater than the specified number.

Cos: Cosine calculation.

DecBin: Convert decimal to binary.

DecHex: Convert decimal to hexadecimal.

DecOct: Convert decimal to octal.

Exp: The power of the natural logarithm e.

Floor: Calculates the largest integer less than the specified number.

getrandmax: The maximum value of the random number.

HexDec: Convert hexadecimal to decimal.

Log: Natural logarithm value.

Log10: Log value of 10 base.

max: Get the maximum value.

min: Get the minimum value.

mt_rand: Get a random value.

mt_srand: Configure random number seed.

mt_getrandmax: The maximum value of random number.

number_format: Format number string.

OctDec: Convert octal to decimal.

pi: Pi.

pow: Power.

rand: Get a random value.

round: Rounding.

Sin: Sine calculation.

Sqrt: Square root.

srand: Configure random number seed.

Tan: Tangent calculation.

2. Function analysis is as follows:

Abs
Get the absolute value.
Syntax: mixed abs(mixed number);
Return value: Mixed type data
Function type: Mathematical operation
Content description: Return the absolute value of parameter number. If number is a multiple-precision floating-point number, the return value is also a multiple-precision floating-point number; for other types, the return type is an integer.

Acos
Get the arc cosine value.
Syntax: float acos(float arg);
Return value: floating point number
Function type: Mathematical operation
Content description: Returns the inverse cosine value (arc cosine) of parameter arg.
Reference: asin() atan()

Asin
Get the inverse sine value.
Syntax: float asin(float arg);
Return value: floating point number
Function type: Mathematical operation
Content description: Returns the inverse sine value (arc sine) of parameter arg.
Reference: acos() atan()

Atan
Get the arctangent value.
Syntax: float atan(float arg);
Return value: floating point number
Function type: Mathematical operation
Content description: Returns the arc tangent value of parameter arg (arc tangent).
Reference: acos() asin()

Atan2
Calculate the arc tangent of a two number.
Syntax: float atan2(float y, float x);
Return value: floating point number
Function type: Mathematical operation
Content description: This function is used to calculate the arc tangent of two numbers y and x value, the calculation result is similar to atan()'s calculation of y/x, but this function will affect the result due to the positive and negative signs of x and y. The return value of this function must fall between positive and negative pi (-PI <= (value) ≶= PI)
Refer to acos() atan() asin()

base_convertThe carry method for converting numbers.
Syntax: string base_convert(string number, int frombase, int tobase);
Return value: String
Function type: Mathematical operation
Content description: This function converts the numeric string number from frombase Carry is converted to carry by tobase. This formula can handle carry modes from binary to hexadecimal. Before the decimal place, it is represented by numbers, and after the decimal place is exceeded, it is represented by English letters. For example, the sequence of hexadecimal single digits is 123456789abcdef, and the sequence of 10 is the seventeenth, and then one digit is carried forward. In hexadecimal a is the tenth, b is the eleventh, z is the thirty-sixth, and 10 is the thirty-seventh, then the carry is carried out.

Usage example

This example converts a hexadecimal string into a binary string

<?php
$binary = base_convert($hexadecimal, 16, 2);
echo "十六进位字符串"$hexadecimal"转成二进位为"$binary"。";
?>

BinDec
Converts a binary string into ten carry.
Syntax: int bindec(string binary_string);
Return value: integer
Function type: Mathematical operation
Content description: This function converts a binary digit string into a decimal integer. Since PHP uses 32-bit signed integers for calculations, the maximum decimal number it can handle is 2147483647, which is 1111111111111111111111111111111 (31 ones) in binary.
Reference: DecBin()

Ceil
Calculate the smallest integer greater than the specified number.
Syntax: int ceil(float number);
Return value: integer
Function type: Mathematical operation
Content description: This function is used to calculate the smallest integer larger than the floating point parameter number.

Usage example

The return value in this example is 4.

<?php
$nextint=ceil(3.14);
echo $nextint;
?>

Reference: Floor() round()

Cos
Cosine calculation.
Syntax: float cos(float arg);
Return value: Floating point number
Function type: Mathematical operation
Content description: This function calculates the cosine value (cosine) of the parameter arg.
Reference: Sin() Tan()

DecBin
十进位转二进位。
语法: string decbin(int number);
返回值: 字符串
函数种类: 数学运算
内容说明: 本函数将十进位数字转成二进位字符串。由于 PHP 使用 32 位有正负号整数计算,能处理的最大十进位数字为 2147483647,也就是二进位数字的 1111111111111111111111111111111 (31 个 1)。
参考: BinDec()

DecHex
十进位转十六进位。
语法: string dechex(int number);
返回值: 字符串
函数种类: 数学运算
内容说明: 本函数将十进位数字转成十六进位字符串。由于 PHP 使用 32 位有正负号整数计算,能处理的最大十进位数字为 2147483647,也就是十六进位数字 7fffffff。
参考: HexDec()

DecOct
十进位转八进位。
语法: string decoct(int number);
返回值: 字符串
函数种类: 数学运算
内容说明: 本函数将十进位数字转成八进位字符串。由于 PHP 使用 32 位有正负号整数计算,能处理的最大十进位数字为 2147483647,也就是八进位数字 17777777777。
参考: OctDec()

Exp
自然对数 e 的次方值。
语法: float exp(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算自然对数 (natural logarithm) 的 arg 次方值。
参考: pow() Log()

Floor
计算小于指定数的最大整数。
语法: int floor(float number);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数用来计算比浮点参数 number 小的最大整数。

使用范例

本例返回值为 3。

<?php
$lastint=floor(3.14);
echo $lastint;
?>

参考: Ceil() round()

getrandmax
乱数的最大值。
语法: int getrandmax(void);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数计算乱数函数 rand() 可能取得的取得的最大乱数值。本函数不需参数。
参考: rand() srand() mt_rand() mt_srand() mt_getrandmax()

HexDec
十六进位转十进位。
语法: int hexdec(string hex_string);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数将十六进位字符串转成十进位数字。由于 PHP 使用 32 位有正负号整数计算,能处理的最大十六进位数字为 7fffffff,也就是十进位数字的 2147483647。
参考: DecHex()

Log
自然对数值。
语法: float log(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算参数 arg 的自然对数 (natural logarithm) 值。

Log10
10 基底的对数值。
语法: float log10(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算参数 arg 的 10 基底对数值。

max
取得最大值。
语法: mixed max(mixed arg1, mixed arg2 .... mixed argn);
返回值: 混合类型资料
函数种类: 数学运算
内容说明: 本函数计算参数间的最大值。若第一个参数是数字数组,则会找出该数组的最大数字。若第一个参数非数组,则需二个以上的参数。这些数字可以是整数、倍精确数或数字字符串的类型。参数的数目不限,视用户的需求而定。在计算时,只要有一个参数是倍精确数,本函数会将所有的参数都转成倍精确数,并返回倍精确数。若参数只有整数及数字字符串,则会将所有的参数转换成整数,并返回整数。
参考: min()

min
取得最小值。
语法: mixed min(mixed arg1, mixed arg2 .... mixed argn);
返回值: 混合类型资料
函数种类: 数学运算
内容说明: 本函数计算参数间的最小值。若第一个参数是数字数组,则会找出该数组的最小数字。若第一个参数非数组,则需二个以上的参数。这些数字可以是整数、倍精确数或数字字符串的类型。参数的数目不限,视用户的需求而定。在计算时,只要有一个参数是倍精确数,本函数会将所有的参数都转成倍精确数,并返回倍精确数。若参数只有整数及数字字符串,则会将所有的参数转换成整数,并返回整数。
参考: max()

mt_rand取得乱数值。
语法: int mt_rand([int min], [int max]);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数不使用一般常用的 libc 来计算乱数值,而是使用计算速度至少快四倍的马其赛特旋转 (Mersenne Twister) 演算法来计算乱数值。有关马特赛特旋转演算法可在松本真的 http://www.math.keio.ac.jp/~matumoto/emt.html 找到更多的相关信息,最佳化的原始程序则在 http://www.scp.syr.edu/~marc/hawk/twister.html。若没有指定乱数的最大及最小范围,本函数会自动的从 0 到 RAND_MAX 中取一个乱数。若有指定 min 及 max 的参数,则从指定参数中取一个数字,例如 mt_rand(38, 49) 则会从 38 到 49 之间取一个乱数值。值得注意的是为使乱数的乱度最大,每次在取乱数之前最好使用 mt_srand() 以配置新的乱数种子。
参考: rand() srand() getrandmax() mt_srand() mt_getrandmax()

mt_srand配置乱数种子。
语法: void mt_srand(int seed);
返回值: 无
函数种类: 数学运算
内容说明: 本函数传入参数 seed 后,配置乱数的种子。值得注意的是参数 seed 值最好也是随机出现的数字,例如利用加入时间做为变量的来源就是不错的方法,或者开发其它的硬体周边界面可取得更好的乱数。

使用范例

本例加入时间的因素,以执行时的百万分之一秒当乱数种子

<?php
mt_srand((double)microtime()*1000000);
$randval = mt_rand();
echo $randval;
?>

参考: rand() srand() getrandmax() mt_rand() mt_getrandmax()

mt_getrandmax乱数的最大值。
语法: int mt_getrandmax(void);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数计算乱数函数 mt_rand() 可能取得的取得的最大乱数值。本函数不需参数。
参考: rand() srand() getrandmax() mt_srand() mt_rand()

number_format格式化数字字符串。
语法: string number_format(float number, int [decimals], string [dec_point], string [thousands_sep]);
返回值: 字符串
函数种类: 数学运算
内容说明: 本函数用来将浮点参数 number 格式化。若没加参数 decimals 则返回的字符串只要整数部份,加了此参数才依参数指定的小数点位数返回。参数 dec_point 表示小数点的表示方式方法,默认值是 ".",若需要转换成其它的小数点就可以在这个参数改掉。参数 thousands_sep 为整数部份每三位的分隔符号,默认值是 ","。本函数最特别的地方就是参数数目,最少要有一个,也就是欲格式化的字符串;也可以有二个或者四个参数,但不能用三个参数。值得注意的是指定小数点的位数之后的数字直接舍弃,没有四舍五入的情形。

使用范例

<?php
$short_pi = "3.14159";
$my_pi = number_format($short_pi, 2);
echo $my_pi."n"; // 3.14
$foo = 850017.9021;
$new_foo = number_format($foo, 3, ".", " ");
echo $new_foo."n"; // 850 017.902
?>

OctDec
八进位转十进位。
语法: string decoct(int number);
返回值: 字符串
函数种类: 数学运算
内容说明: 本函数将八进位字符串转成十进位数字。由于 PHP 使用 32 位有正负号整数计算,能处理最大的八进位数字为 17777777777,也就是十进位数字的 2147483647。
参考: DecOct()

pi圆周率。
语法: double pi(void);
返回值: 倍精确数
函数种类: 数学运算
内容说明: 本函数返回圆周率。不需输入参数。

pow次方。
语法: float pow(float base, float exp);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算次方值。参数 base 为基底,exp 为幂数。

使用范例

<?php
print(pow(2,3)); // 8
print(pow(5,4)); // 625
?>

参考: Log10() Exp()

rand
取得随机数值。
语法: int rand([int min], [int max]);
返回值: 整数
函数种类: 数学运算
内容说明: 本函数用来取得随机数值。若没有指定随机数的最大及最小范围,本函数会自动的从 0 到 RAND_MAX 中取一个随机数。若有指定 min 及 max 的参数,则从指定参数中取一个数字。例如 rand(38, 49) 则会从 38 到 49 之间取一个随机数值,UNIX 系统包含 49、Win32 系统不包含 49 ([email=zkimmel@earthlink.net]zkimmel@earthlink.net[/email] 10-May-1999)。值得注意的是为使随机数的乱度最大,每次在取随机数之前最好使用 srand() 以配置新的随机数种子。
参考: srand() getrandmax() mt_rand() mt_srand() mt_getrandmax()

round
四舍五入。
语法: double round(double val);
返回值: 倍精确数
函数种类: 数学运算
内容说明: 本函数用来将数字小数点后四舍五入。

使用范例

<?php
$foo1 = round(3.4);
$foo2 = round(3.5);
$foo3 = round(3.6);
echo "round(3.4): ".$foo1."<br>n";
echo "round(3.5): ".$foo2."<br>n";
echo "round(3.6): ".$foo3;
?>

参考: Ceil() Floor()

Sin正弦计算。
语法: float sin(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算参数 arg 的正弦值 (sine)。
参考: Cos() Tan()

Sqrt
开平方根。
语法: float sqrt(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数将参数 arg 开平方根。

srand
配置随机数种子。
语法: void srand(int seed);
返回值: 无
函数种类: 数学运算
内容说明: 本函数传入参数 seed 后,配置随机数的种子。值得注意的是参数 seed 值最好也是随机出现的数字,例如利用加入时间做为变量的来源就是不错的方法,或者开发其它的硬体周边界面可取得更好的随机数。

使用范例

本例加入时间的因素,以执行时的百万分之一秒当随机数种子

<?php
srand((double)microtime()*1000000);
$randval = rand();
echo $randval;
?>

参考: rand() getrandmax() mt_srand() mt_rand() mt_getrandmax()

Tan
正切计算。
语法: float tan(float arg);
返回值: 浮点数
函数种类: 数学运算
内容说明: 本函数计算参数 arg 的正切值 (tangent)。
参考: Sin() Cos()

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP获取表单数据与HTML嵌入PHP脚本的实现

PHP实现数据分页显示的方法及简单实例

php中关于长度计算容易混淆的问题简单分析

The above is the detailed content of Functions and example analysis of PHP mathematical operation functions. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
4 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Simple Guide to PHP Setup A Simple Guide to PHP Setup Jul 18, 2025 am 04:25 AM

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

See all articles