PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<mailparse_uudecode_allabs>
view the version of this page
Last updated: Sat, 19 Apr 2003

LI. Mathematische Funktionen

Einleitung

Die mathematischen Funktionen behandeln nur Werte im Bereich der Datentypen long und double der jeweiligen Architektur. Wenn Sie gr��ere Zahlen oder Werte mit h�herer Genauigkeit ben�tigen, sollten Sie sich die mathematische Funktionen mit beliebiger Genauigkeit ansehen.

Mathematische Konstanten

Die folgenden Werte werden von diesem Packet definiert:

Tabelle 1. Mathematische Konstanten

KonstanteWertBeschreibung
M_PI3.14159265358979323846Der Wert � (Pi)
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_2_SQRTPI1.128379167095512573902/sqrt(pi)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT1_20.707106781186547524401/sqrt(2)
Bis auf M_PI sind diese Konstanten erst ab PHP4.0 verf�gbar.

Inhaltsverzeichnis
abs -- Absolutwert
acos -- Arcuscosinus
acosh -- Inverse hyperbolic cosine
asin -- Arcussinus
asinh -- Inverse hyperbolic sine
atan2 -- Arcustangens aus zwei Werten
atan -- Arcustangens
atanh -- Inverse hyperbolic tangent
base_convert -- Konvertiert Werte zwischen Zahlensystemen unterschiedlicher Basis
bindec -- Bin�r zu dezimal Konvertierung
ceil -- Aufrunden
cos -- Cosinus
cosh -- Hyperbolic cosine
decbin -- Dezimal zu bin�r Konvertierung
dechex -- Dezimal zu hexadezimal Konvertierung
decoct -- Dezimal zu oktal Konvertierung
deg2rad -- Grad in Bogenma� wandeln
exp -- e hoch ...
expm1 --  Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
floor -- Abrunden
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- Gr��tm�glicher Zufallswert
hexdec -- Hexadezimal zu dezimal Konvertierung
hypot --  Returns sqrt( num1*num1 + num2*num2)
is_finite -- 
is_infinite -- 
is_nan -- 
lcg_value -- Combined linear congruential generator
log10 -- Zehner-Logarithmus
log1p --  Returns log(1 + number), computed in a way that accurate even when the val ue of number is close to zero
log -- Nat�rlicher Logarithmus
max -- Maximalwert bestimmen
min -- Minimalwert bestimmen
mt_getrandmax -- show largest possible random value
mt_rand -- Erzeugt 'bessere' Zufallszahlen
mt_srand -- seed the better random number generator
octdec -- Oktal zu dezimal Konvertierung
pi -- Wert von PI
pow -- Exponentialfunktion
rad2deg -- Bogenma� in Grad wandeln
rand -- (Pseudo-) Zufallszahl generieren
round -- Runden eines Wertes
sin -- Sinus
sinh -- Hyperbolic sine
sqrt -- Quadratwurzel
srand -- Startwert f�r den Zufallsgenerator festlegen
tan -- Tangens
tanh -- Hyperbolic tangent


User Contributed Notes
Mathematische Funktionen
add a note
cathody at mail dot ru
11-Aug-2000 02:55

Converting non-standard form:

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

ian at mp3 dot com
19-Feb-2001 10: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;
}

cornelius at skjoldhoej dot dk
12-Jun-2001 09:03


I found that when dealing with tables, a 'least common multiple' function is sometimes useful for abusing tablespan and the likes.

So here goes (you may choose to remove the first part of the gcd function if the function call is well-behaved):
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));
}

This may or may not be something to consider adding to the mathematical function library.

webkid%webkid.com
31-May-2002 10: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.

webkid%webkid.com
31-May-2002 10: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!

shanx at shanx dot com
08-Jul-2002 08: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 ([email protected])
* @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);

?>

lepkio at spanltd dot com
11-Jul-2002 12:13

I couldn't have found mod function, but it is there as % sign.  For example; 6%3=0, 7%3=1 and so on.
Oliver Lepki

patience at worldonline dot nl
05-Aug-2002 04: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 );
}

jbeardsl [found_at] gte [d0t] net
08-Nov-2002 08: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);
}

jbeardsl at gte dot net
09-Nov-2002 05: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);

}

nazgul26 (at_sign) windfox dot net
08-Dec-2002 09: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>";
}
}

php at casaforge dot com (Hal)
01-Feb-2003 12: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>';

?>

jl85 at yahoo dot com
22-Feb-2003 03: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.

jerry dot wilborn at fast dot net
16-Apr-2003 06: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));

matthew_gaddis at yahoo dot com
24-Apr-2003 09:23

Here is a cleaner factorial function:

function factorial($s){
if($s) $r = $s * factorial($s - 1);
else $r = 1;
return $r;
}

add a note

<mailparse_uudecode_allabs>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Wed May 14 01:12:44 2003 CEST