|
|
LXXVIII. Математические функцииЭти функции всегда доступны. Для использования этих функций не требуется проведение установки,
поскольку они являются частью ядра PHP. Данное расширение не определяет никакие директивы конфигурации в php.ini. Данное расширение не определяет никакие типы ресурсов.
Перечисленные ниже константы всегда доступны как часть ядра PHP.
Таблица 1. Математические константы | Константа | Значение | Описание |
|---|
| M_PI | 3.14159265358979323846 | число пи | | M_E | 2.7182818284590452354 | число Эйлера | | M_LOG2E | 1.4426950408889634074 | log_2 e | | M_LOG10E | 0.43429448190325182765 | lg e | | M_LN2 | 0.69314718055994530942 | ln 2 | | M_LN10 | 2.30258509299404568402 | ln 10 | | M_PI_2 | 1.57079632679489661923 | пи/2 | | M_PI_4 | 0.78539816339744830962 | пи/4 | | M_1_PI | 0.31830988618379067154 | 1/пи | | M_2_PI | 0.63661977236758134308 | 2/пи | | M_SQRTPI | 1.77245385090551602729 | sqrt(пи) [4.0.2] | | M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(пи) | | M_SQRT2 | 1.41421356237309504880 | sqrt(2) | | M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2] | | M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) | | M_LNPI | 1.14472988584940017414 | ln пи [4.0.2] | | M_EULER | 0.57721566490153286061 | Постоянная эйлера [4.0.2] |
В версиях PHP до 4.0.0 включительно доступна только M_PI.
Все остальные были добавлены с следующей версии, кроме констант с пометкой [4.0.2], которые были добавлены в версии PHP 4.0.2.
- Содержание
- abs -- Модуль числа
- acos -- Arc cosine
- acosh -- Inverse hyperbolic cosine
- asin -- Arc sine
- asinh -- Inverse hyperbolic sine
- atan2 -- Arc tangent of two variables
- atan -- Arc tangent
- atanh -- Inverse hyperbolic tangent
- base_convert -- Convert a number between arbitrary bases
- bindec -- Binary to decimal
- ceil -- Округляет дробь в большую сторону
- cos -- Cosine
- cosh -- Hyperbolic cosine
- decbin -- Decimal to binary
- dechex -- Decimal to hexadecimal
- decoct -- Decimal to octal
- deg2rad --
Converts the number in degrees to the radian equivalent
- exp -- Calculates the exponent of e
- expm1 --
Returns exp(number) - 1, computed in a way that is accurate even
when the value of number is close to zero
- floor -- Округляет дробь в меньшую сторону
- fmod -- Возвращает дробный остаток от деления
- getrandmax -- Вовзращает максимально возможное случайное число
- hexdec -- Hexadecimal to decimal
- hypot --
Calculate the length of the hypotenuse of a right-angle triangle
- is_finite -- Finds whether a value is a legal finite number
- is_infinite -- Finds whether a value is infinite
- is_nan -- Finds whether a value is not a number
- lcg_value -- Combined linear congruential generator
- log10 -- Base-10 logarithm
- log1p --
Returns log(1 + number), computed in a way that is accurate even when
the value of number is close to zero
- log -- Natural logarithm
- max -- Находит наибольшее значение
- min -- Находит наименьшее значение
- mt_getrandmax -- Show largest possible random value
- mt_rand -- Generate a better random value
- mt_srand -- Seed the better random number generator
- octdec -- Octal to decimal
- pi -- Возвращает число Пи
- pow -- Exponential expression
- rad2deg --
Converts the radian number to the equivalent number in degrees
- rand -- Генерирует случайное число
- round -- Округляет число типа float
- sin -- Sine
- sinh -- Hyperbolic sine
- sqrt -- Square root
- srand -- Изменяет начальное число генератора псевдослучайных чисел
- tan -- Tangent
- tanh -- Hyperbolic tangent
add a note
User Contributed Notes
Математические функции
ddarjany at yahoo dot com
05-Sep-2007 10:25
Tim's fix of Evan's ordinal function causes another problem, it no longer works for number above 100. (E.g. it returns 111st instead of 111th).
Here is a further modified version which should work for all numbers.
<?PHP
function ordinal($cardinal) {
$cardinal = (int)$cardinal;
$digit = substr($cardinal, -1, 1);
if ($cardinal <100) $tens = round($cardinal/10);
else $tens = substr($cardinal, -2, 1);
if($tens == 1) {
return $cardinal.'th';
}
switch($digit) {
case 1:
return $cardinal.'st';
case 2:
return $cardinal.'nd';
case 3:
return $cardinal.'rd';
default:
return $cardinal.'th';
}
}
?>
11-Apr-2007 11:55
Here is another way of calculating the nth term of the Fibonacci sequence, based on Binet's formula (see http://en.wikipedia.org/wiki/Fibonacci_series#Closed_form_expression for more information on this).
In this example, it would display the 17th term of the Fibonacci sequence.
<?php
$n = 17; $phi = (1 + sqrt(5)) / 2; $u = (pow($phi, $n) - pow(1 - $phi, $n)) / sqrt(5);
echo "U<sub>$n</sub> = $u";
?>
Here is a script that lists the Fibonacci sequence from whatever two terms you specify, in this example from the 12th term to the 27th term (inclusive).
<?php
$f = 12; $t = 27; $phi = (1 + sqrt(5)) / 2; while($f <= $t) {
$u = (pow($phi, $f) - pow(1 - $phi, $f)) / sqrt(5);
echo "U<sub>$f</sub> = $u<br>\n";
$f++;
}
?>
barry at megaspace dot com
02-Dec-2006 09:14
Here's a least common denominator (lcd) function:
$array = array(3,4,6,8,18,2);
function lcd($array,$x) {
$mod_sum = 0;
for($int=1;$int < count($array);$int++) {
$modulus[$int] = ($array[0]*$x) % ($array[$int]);
$mod_sum = $mod_sum + $modulus[$int];
}
if (!$mod_sum) {
echo "LCD: ".($array[0]*$x)."\n";
}
else {
lcd($array,$x+1);
}
}
lcd($array,1);
tembenite at gmail dot com
06-Nov-2006 01:36
To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:
function lcm_arr($items){
//Input: An Array of numbers
//Output: The LCM of the numbers
while(2 <= count($items)){
array_push($items, lcm(array_shift($items), array_shift($items)));
}
return reset($items);
}
//His Code below with $'s added for vars
function gcd($n, $m) {
$n=abs($n); $m=abs($m);
if ($n==0 and $m==0)
return 1; //avoid infinite recursion
if ($n==$m and $n>=1)
return $n;
return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n);
}
function lcm($n, $m) {
return $m * ($n/gcd($n,$m));
}
tim at durge dot org
27-Oct-2006 05:51
In Evan's ordinal function, the line:
<?php
$tens = substr($cardinal, -2, 1);
?>
needs to be replaced by:
<?php
$tens = round($cardinal/10);
?>
or similar. At least on PHP 4.3.10, substr("1", -2, 1) returns '1' - so Evan's function gives "1th", as well as "11th". This is contrary to the documentation, but is noted in the comments on the substr manual page.
Evan Broder
26-Jul-2006 11:42
A slightly more complex but much more accurate cardinal=>ordinal function (the one below doesn't account for 11th, 12th, and 13th, which don't follow the usual rules):
<?php
function ordinal($cardinal)
{
$cardinal = (int)$cardinal;
$digit = substr($cardinal, -1, 1);
$tens = substr($cardinal, -2, 1);
if($tens == 1)
{
return $cardinal.'th';
}
switch($digit)
{
case 1:
return $cardinal.'st';
case 2:
return $cardinal.'nd';
case 3:
return $cardinal.'rd';
default:
return $cardinal.'th';
}
}
?>
edward at edwardsun dot com
19-Jul-2006 06:24
well just a note.. maybe i'm a bit stupid.. but remember to use pow() rather than the "^" sign for exponents.. as it took me 5 minutes to figure out why it wasn't working.
jaakko dot mantila at sagas dot fi
12-Jul-2006 03:10
Here is another payment function with working future value($fv) option:
function payment($r,$np,$pv,$fv,$prec) {
/* Calculates the monthly payment
** $apr = the annual percentage rate of the loan.
** $n = number of monthly payments (360 for a 30year loan)
** $pv = present value or principal of the loan
** $fv = future value of the loan (after payments)
** $prec = the precision you wish rounded to
*/
/****************************************\
** No Warranty is expressed or implied. **
*****************************************/
if(!$fv) $fv = 0;
$mypmt=$r * (-$fv+pow((1+$r),$np)*$pv)/(-1+pow((1+$r),$np));
return round($mypmt, $prec);
}
twoscoopsofpig at NOSPAM dot gmail dot com
07-Jul-2006 09:07
@ Moikboy:
This may or may not be more simplified factorialization:
<?php
$f=$fact=25;
while ($fact>0)
{$f=$f*$fact--;}
echo $f;
?>
marasek.SPAMLESS at telton.de
08-Jun-2006 05:23
I could not resist to do a simpler version of the ordinal function:
<?php
function ordinal($num)
{
$num = (int)$num;
$digit = substr($num, -1, 1);
$ord = "th";
switch($digit)
{
case 1: $ord = "st"; break;
case 2: $ord = "nd"; break;
case 3: $ord = "rd"; break;
break;
}
return $num.$ord;
}
?>
One could replace the typecast with
<?php
if($num===NULL or $num==="")
{return NULL;}
?>
to get an empty result instead of "0th" in case $num is empty too.
moikboy (nospam!) moikboy (nospam!) hu
10-May-2006 01:15
I think, this is the optimal code for calculating factorials:
<?php
function fact($int){
if($int<2)return 1;
for($f=2;$int-1>1;$f*=$int--);
return $f;
};
?>
And another one for calculating the $int-th Fibonacci-number:
<?php
function fib($int){
static $fibTable=array();
return empty($fibTable[$int])?$fibTable[$int] = $int>1?fib($int-2)+fib($int-1):1:$fibTable[$int];
};
?>
nessthehero at comcast dot net
21-Mar-2006 02:48
Just a simple function to find the ordinal ending to any number if you're printing for example: "The nth result is..."
function ordinal($num) {
$digit = substr($num,-1,1);
$ord = array(
0 => 'th',
1 => 'st',
2 => 'nd',
3 => 'rd',
4 => 'th',
5 => 'th',
6 => 'th',
7 => 'th',
8 => 'th',
9 => 'th'
);
$string = $num.$ord[$digit];
return $string;
}
Florian
03-Mar-2006 01:36
A function that simulates the sum operator. (http://en.wikipedia.org/wiki/Sum). Be careful with the expression because it may cause a security hole; note the single quotes to don't parse the "$".
<?php
function sum($expr,$var,$start,$end,$step = 1) {
$expr = str_replace(';','',$expr);
$var = str_replace('$','',$var);
$start = (int)$start; $end = (int)$end; $step = (int)$step; $sum = 0;
for ($i = $start; $i <= $end; $i = $i + $step) {
$_expr = str_replace('$'.$var,$i,$expr);
$_eval = '$_result = '.$_expr.'; return $_result;';
$_result = eval($_eval);
if($result === FALSE) return "SYNTAX ERROR : $expr";
$sum += $_result;
}
return (int)$sum;
}
?>
jos at gtacrime dot nl
17-Feb-2006 01:39
Thanks to Chronial "at" cyberpunkuniverse.de, I was able to create the binompdf(n, p, k) function.
<?php
function nCr($n, $k){
if ($k > $n)
return NaN;
if (($n - $k) < $k)
return nCr($n, ($n - $k));
$return = 1;
for ($i=0; $i<$k; $i++){
$return *= ($n - $i) / ($i + 1);
}
return $return;
}
function binompdf($n, $p, $k){
$return = nCr($n, $k) * pow($p, $k) * pow((1 - $p), ($n - $k));
return $return;
}
?>
peter-stangl at t-online dot de
01-Feb-2006 03:16
I needed to approximate an integral because i was not able to calculate it, so i wrote this function. It approximates an integral with the composite Simpson's rule.
More information on Simpson's rule: http://en.wikipedia.org/wiki/Simpson%27s_rule
<?php
function simpsonf($x){
return(pow((1+pow($x, (-4))), 0.5));
}
function simpsonsrule($a, $b, $n){
if($n%2==0){
$h=($b-$a)/$n;
$S=simpsonf($a)+simpsonf($b);
$i=1;
while($i <= ($n-1)){
$xi=$a+$h*$i;
if($i%2==0){
$S=$S+2*simpsonf($xi);
}
else{
$S=$S+4*simpsonf($xi);
}
$i++;
}
return($h/3*$S);
}
else{
return('$n has to be an even number');
}
}
?>
|