Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

LXXVIII. Математические функции

Введение

Данные функции работают с числами в диапазонах типов integer и float на вашей машине (это отвечает C-типам long и double). Если вам нужно работать с большими числами, обратитесь к разделу Ссылка VII, BCMath Arbitrary Precision Mathematics Functions.

См. также Разд. Арифметические операторы в Гл. 15.

Требования

Эти функции всегда доступны.

Установка

Для использования этих функций не требуется проведение установки, поскольку они являются частью ядра PHP.

Настройка во время выполнения

Данное расширение не определяет никакие директивы конфигурации в php.ini.

Типы ресурсов

Данное расширение не определяет никакие типы ресурсов.

Предопределенные константы

Перечисленные ниже константы всегда доступны как часть ядра PHP.

Таблица 1. Математические константы

КонстантаЗначениеОписание
M_PI3.14159265358979323846число пи
M_E2.7182818284590452354число Эйлера
M_LOG2E1.4426950408889634074log_2 e
M_LOG10E0.43429448190325182765lg e
M_LN20.69314718055994530942ln 2
M_LN102.30258509299404568402ln 10
M_PI_21.57079632679489661923пи/2
M_PI_40.78539816339744830962пи/4
M_1_PI0.318309886183790671541/пи
M_2_PI0.636619772367581343082/пи
M_SQRTPI1.77245385090551602729sqrt(пи) [4.0.2]
M_2_SQRTPI1.128379167095512573902/sqrt(пи)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT31.73205080756887729352sqrt(3) [4.0.2]
M_SQRT1_20.707106781186547524401/sqrt(2)
M_LNPI1.14472988584940017414ln пи [4.0.2]
M_EULER0.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


abs> <mailparse_uudecode_all
Last updated: Fri, 26 Jan 2007
 
add a note 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; // Sets a value for $n, the nth term
$phi = (1 + sqrt(5)) / 2; // Sets the value of phi for use in the formula
$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; // Sets the 'f'th term, the term from which to start listing
$t = 27; //Sets the 't'th term, the term at which to stop listing
$phi = (1 + sqrt(5)) / 2; // Sets the value of phi for use in the formula
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
# @param    string    $expr    expression to evaluate (for example (2*$x)^2+1)
# @param    string    $var      dummy variable (for example "x")
# @param    integer    $start
# @param    integer    $end
# @param    integer    $step

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){
// returns f(x) for integral approximation with composite Simpson's rule
  
return(pow((1+pow($x, (-4))), 0.5));
}
function
simpsonsrule($a, $b, $n){
// approximates integral_a_b f(x) dx with composite Simpson's rule with $n intervals
// $n has to be an even number
// f(x) is defined in "function simpsonf($x)"
  
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');
   }
}

?>
daniel at g-loc dot org
01-Dec-2005 10:01
If you
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Юбки топы юбки выбирайте купить шорты шорты ; casino gambling online top Z058440144362 Z348613067571