PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<mailparse_uudecode_allabs>
view the version of this page
Last updated: Sun, 02 May 2004

LII. Funzioni Matematiche

Introduzione

Queste funzioni matematiche operano esclusivamente nel range dei tipi di dato integer e float del computer. (questo corrisponde attualmente ai tipi di dati long e double del C) Se si ha necessità di lavorare con numeri più grandi, fare riferimento alle funzioni matematiche a precisione arbitraria.

Vedere anche il manuale alle pagine operatori aritmetici.

Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.

Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.

Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini

Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.

Costanti predefinite

Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.

Tabella 1. Costanti Matematiche

CostanteValoreDescrizione
M_PI3.14159265358979323846Pi
M_E2.7182818284590452354e
M_LOG2E1.4426950408889634074log_2 e
M_LOG10E0.43429448190325182765log_10 e
M_LN20.69314718055994530942log_e 2
M_LN102.30258509299404568402log_e 10
M_PI_21.57079632679489661923pi/2
M_PI_40.78539816339744830962pi/4
M_1_PI0.318309886183790671541/pi
M_2_PI0.636619772367581343082/pi
M_SQRTPI1.77245385090551602729sqrt(pi) [4.0.2]
M_2_SQRTPI1.128379167095512573902/sqrt(pi)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT31.73205080756887729352sqrt(3) [4.0.2]
M_SQRT1_20.707106781186547524401/sqrt(2)
M_LNPI1.14472988584940017414log_e(pi) [4.0.2]
M_EULER0.57721566490153286061Costante di Eulero [4.0.2]
Soltanto M_PI è disponibile nelle versioni precedenti alla PHP 4.0.0 (compresa). Tutte le rimanenti costanti sono disponibili a partire dal PHP 4.0.0. Le costanti indicate con [4.0.2] sono state aggiunte nel PHP 4.0.2.

Sommario
abs -- Valore assoluto
acos -- Arco coseno
acosh -- Inverso del coseno iperbolico
asin -- Arco seno
asinh -- Inverso del seno iperbolico
atan2 -- Arco tangente di due variabili
atan -- Arco tangente
atanh -- Inverso della tangente iperbolica
base_convert -- Converte un numero fra basi arbitrarie
bindec -- Da binario a decimale
ceil -- arrotonda le frazioni all'intero superiore
cos -- Coseno
cosh -- Coseno iperbolico
decbin -- Da decimale a binario
dechex -- Da decimale a esadecimale
decoct -- Da decimale a ottale
deg2rad --  Converte il numero dato in gradi nell'equivalente espresso in radianti
exp -- Calcola l'esponente di e (la base logaritmica naturale o di Nepero)
expm1 --  Restituisce exp(numero) - 1, computato in maniera tale da essere accurato anche se il valore del numero è vicino a zero
floor -- Arrotonda le frazioni all'intero inferiore
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- Mostra il più grande numero casuale disponibile
hexdec -- Da esadecimale a decimale
hypot --  Restituisce sqrt(num1*num1 + num2*num2)
is_finite -- Verifica se un numero dato è un numero finito
is_infinite -- Verifica se un dato valore è infinito
is_nan -- Verifica se un dato valore non sia un numero
lcg_value -- Generatore combinato lineare congruenziale
log10 -- Logaritmo base-10
log1p --  Restituisce log(1 + numero), computato in maniera tale da essere accurato anche se il valore del numero è vicino a zero
log -- Logaritmo naturale
max -- Trova il valore massimo
min -- Trova il valore minimo
mt_getrandmax -- Mostra il più grande valore casuale disponibile
mt_rand -- Genera un valore casuale migliore
mt_srand -- Inizializza un generatore di numeri casuali migliore
octdec -- Da ottale a decimale
pi -- Restituisce il valore di pi
pow -- Espressione esponenziale
rad2deg --  Converte un numero in radianti nell'equivalente numero in gradi
rand -- Genera un valore casuale
round -- Arrotonda un numero non intero
sin -- Seno
sinh -- Seno iperbolico
sqrt -- Radice quadrata
srand -- inizializza il generatore di numeri casuali
tan -- Tangente
tanh -- Tangente iperbolica


add a note add a note User Contributed Notes
Funzioni Matematiche
ausvald at tut dot by
30-Apr-2004 11:48
I see there are some factorial functions below.

I'll provide the best one:

<?
function factorial($n){ $n=(int)$n;
 
$f=1;
  for(;
$n>0;--$n) $f*=$n;
  return
$f;
}
?>
florian at shellfire dot de
28-Apr-2004 08:48
Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

<?php

  
// Calculate the Faculty of a positive int-value
  
function iFaculty($a_iFac)
   {
     if (
$a_iFac > 0)
     {
         return
$a_iFac * $this->iFaculty($a_iFac - 1);
     }
     elseif (
$a_iFac == 0)
     {
         return
1;
     }
     else
     {
         return
0// Wrong argument!
    
}
   }
?>

I've also written another function to calculate the
binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!)

<?php

  
// calculates the binomial coefficient "n over k" of 2 positive int values
   // für n >= k
  
function iBinCoeff($a_iN, $a_iK)
   {
      
// the binomial coefficient is defined as n! / [ (n-k)! * k! ]
      
return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK));   
   }

?>
Chronial "at" cyberpunkuniverse.de
13-Jan-2004 07:47
Here are are a nPr and a nPc function
(had to define NaN - don't know, how to this the "rigth" way)

<?php
define
(NaN,acos(1.01));

function
nCr($n,$r){
   if (
$r > $n)
     return
NaN;
   if ((
$n-$r) < $r)
     return
nCr($n,($n-$r));
  
$return = 1;
   for (
$i=0;$i < $r;$i++){
    
$return *= ($n-$i)/($i+1);
   }
   return
$return;
}

function
nPr($n,$r){
   if (
$r > $n)
     return
NaN;
   if (
$r)
     return
$n*(nPr($n-1,$r-1));
   else
     return
1;
}
?>
chris at free-source dot com
07-Oct-2003 03:37
to "convert" scientific notation to a float simply cast it:
<?php
$val
= '3.5e4';
$val = (float) $val;
echo
$val;
?>

output:
35000
jl85 at yahoo dot com
05-Oct-2003 10:00
Here's yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m){
if(!$m)return$n;return gcd($m,$n%$m);
}

It works by recursion. Not really sure about it's speed, but it's really small! This won't work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m){
if(!$m)return$n;return gcd($m,fmod($n,$m));
}
fabien_mornand at yahoo dot fr
30-Sep-2003 09:46
here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I've converted it in php for the fun.

<?php
 
if($a && $b)
  {
$ax=$a; $bx=$b;
  
$r=fmod($a,$b);
  if(!
$r){$rx=$r;}
   while(
$r){
  
$rx=$r;
  
$a=$b;
  
$b=$r;
  
$r=fmod($a,$b);
   }
   }
echo
'PGCD ('.$ax.' , '.$bx.' ) = '.$rx;
?>
jordanolsommer at imap dot cc
27-Aug-2003 02:07
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.

So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).

a clever way of doing things, but $num % 2 would work as well i think :).
matthew_gaddis at yahoo dot com
24-Apr-2003 08:23
Here is a cleaner factorial function:

function factorial($s){
   if($s) $r = $s * factorial($s - 1);
   else $r = 1;
   return $r;
}
jerry dot wilborn at fast dot net
16-Apr-2003 05:10
Here is how to calculate standard deviation in PHP where $samples is an array of incrementing numeric keys and the values are your samples:

$sample_count = count($samples);

for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) $sample_square[$current_sample] = pow($samples[$current_sample], 2);

$standard_deviation = sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2));
jl85 at yahoo dot com
22-Feb-2003 02:04
Theres another faster way of doing even/odd number checking by using bitwise operators. Don't ask me how it works, I just found this out by experimenting with it (could the editor possibly explain?)

if ((1&$num)) {
 echo "$num is odd";
}

if (!(1&$num)) {
 echo "$num is even";
}

How it works is (1&$num) returns a 1 for odd numbers and returns 0 when it's an even number.
php at casaforge dot com (Hal)
31-Jan-2003 11:25
This might be useful in generating fractional numbers for construction, if only because most carpenters would rather put a nail in your foot than hear about any number that ends with .8125".

Since I couldn't figure out the fraction code above, this is my simple-minded take on the problem. Also, align by "char" doesn't seem to work yet in html, so it seems necessary to use tables (egad!) to make numbers align properly. The following code illustrates a way to make a dynamically sized table with aligned fractions from an array of random numbers. Since I don't care about fractions less than 1/16, this rounds them into oblivion. Also, it sorts the list from long to short and collates multiples in the array. One bit of cleverness here (gleaned from these pages) that might not be obvious: I'm using 1 *bitwise and* (1 &) to determine odd numbers.

If you copy and paste the following code, try refreshing the page a few times to see how the table adjusts itself.

<?php

// get some numbers to play with

$x = rand(0,130000)/10;
$y = rand(0,1200);
$z = rand(0,4)/64;
$array = array($x, $x, $x, $y, $y, $z, 324.19, 425/7, sqrt(2), pi(), pi());

// functions

function mult($n) { return intval (round ($n*16)); }

function
frac($num) { $mod = fmod ($num,1)*16;
if (
1 & $mod) { return " - ".$mod."/16"; }
else
$mod = $mod/2;
if (
1 & $mod) { return " - ".$mod."/8"; }
else
$mod = $mod/2;
if (
1 & $mod) { return " - ".$mod."/4"; }
else
$mod = $mod/2;
if (
1 & $mod) {return " - ".$mod."/2";}
}

// make a table

echo '<table>';
$array = array_map("mult", $array);
$array = (array_filter($array, strval)); //get rid of zeros
$array = (array_count_values ($array));
krsort ($array);
while (list (
$key, $val) = each ($array)) {
$key = $key/16;
echo
"<tr><td>$val</td><td>&nbsp; @ &nbsp;</td><td align=\"right\">".intval($key)." </td><td> ".frac($key)." </td></tr>";
}
echo
'</table>';

?>
nazgul26 (at_sign) windfox dot net
08-Dec-2002 08:58
This code will convert a decimal to it's fraction equivalent. The precision can be set by changing PRECISION.

-----------------------------------------------------------------

define(PRECISION, .01);

$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);

echo $simpl_fract;

// Start of functions

/*
   Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
   $a = (1/$decimal);
   $b = ( $a - floor($a)  );
   $count++;
   if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
   $result[$count] = floor($a);
}

/*
   Simplifies a fraction in an array form that is returned from 
   decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
   $next = $fraction[$count-1];
   $a = ($bottom * $next) + $top;
   $top = $bottom;
   $bottom = $a;
   $count--;
   if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
   else {
       return "<font size=1>$bottom/$top</font>";
   }
}
jbeardsl at gte dot net
09-Nov-2002 04:36
I needed a truncate function to operate on real numbers. I preferred not to use a string-manipulation method, so here's my solution. HTH...

function truncate ($num, $digits = 0) {

   //provide the real number, and the number of
   //digits right of the decimal you want to keep.

   $shift = pow(10 , $digits);
   return ((floor($num * $shift)) / $shift);

}
jbeardsl [found_at] gte [d0t] net
08-Nov-2002 07:15
I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it's faster than the alternative of using string functions. HTH...

function truncate ($num, $digits = 0) {

   //provide the real number, and the number of
   //digits right of the decimal you want to keep.

   $shift = pow(10, $digits);
   return ((floor($num * $shift)) / $shift);
}
patience at worldonline dot nl
05-Aug-2002 03:08
The example for Factorials given above is wrong. Here a correct version, so that you do not have to reinvent the wheel again...

function mathFact( $s )
{
  $r = (int) $s;

  if ( $r < 2 )
   $r = 1;
  else {
   for ( $i = $r-1; $i > 1; $i-- )
     $r = $r * $i;
  }

  return( $r );
}
shanx at shanx dot com
08-Jul-2002 07:13
<?

/**
 * Function to calculate base36 values from a number. Very
 * useful if you wish to generate IDs from numbers.
 *
 * @param $value The number
 * @param $base The base to be applied (16, 36 or 64)
 * @return The calculated string
 * @author Shashank Tripathi (shanx@shanx.com)
 * @version 0.1 - Let me know if something doesnt work
 *
 */
 
function base36($value, $base)
{
  
$baseChars = array('0', '1', '2', '3', '4', '5',
                      
'6', '7', '8', '9', 'a', 'b',
                      
'c', 'd', 'e', 'f', 'g', 'h',
                      
'i', 'j', 'k', 'l', 'm', 'n',
                      
'o', 'p', 'q', 'r', 's', 't',
                      
'u', 'v', 'w', 'x', 'y', 'z'
                    
);

  
$remainder = 0;
  
$newval = "";
  
   while (
$value > 0 )
   {
      
$remainder = $value % $base;
      
$value = ( ($value - $remainder)/ $base );
      
$newval .= $baseChars[$remainder];
   }
   return
strrev($newval);
  
}

echo
"The string for 46655, for instance, is " . base36(46655, 36);

?>
webkid%webkid.com
31-May-2002 09:54
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
webkid%webkid.com
31-May-2002 09:49
I found it kind of irritating that PHP had no native functionality for a calculating Factorials. Since I really didn't feel like loading the GMP library, I figured I'd write my own function.

function fact($s){$r=(int)$s; for ($i=$r;$i--;$i>1){$r=$r*$i;} return $r;}

I think that's right... I havn't tested it extensively but it should work.
cornelius at skjoldhoej dot dk
12-Jun-2001 08:03
<P>I found that when dealing with tables, a 'least common multiple' function is sometimes useful for abusing tablespan and the likes.</P>
<P>So here goes (you may choose to remove the first part of the gcd function if the function call is well-behaved):</P>
   function gcd(n, m) //greatest common divisor
   {
       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) //least common multiple
   {
       return m*(n/gcd(n,m));
   }
<P>This may or may not be something to consider adding to the mathematical function library.</P>
ian at mp3 dot com
19-Feb-2001 09:43
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm:

$valid = 1;

$numOfDigits = 0 - strlen($ccNumber);

$i = -1;
while ($i>=$numOfDigits){
  if (($i % 2) == 0){
   $double = 2*(substr($ccNumber, $i, 1));
   $total += substr($double,0,1);
   if (strlen($double > 1)){
     $total += substr($double,1,1);
   }
  } else {
   $total += substr($ccNumber, $i, 1);
  }
  $i--;
}

if (($total % 10) != 0){
  $valid = 0;
}
cathody at mail dot ru
11-Aug-2000 01:55
Converting non-standard form:

you can use something like this:
$v=0.3e-9;
$v=sprintf ( "%2.9f", $v);

<mailparse_uudecode_allabs>
 Last updated: Sun, 02 May 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: Italia OnLine S.p.a.
Last updated: Fri May 21 04:11:23 2004 CEST