- Работа с числами в PHP
- Проверка переменных
- Является ли переменная числом
- Целое или число с плавающей точкой
- Положительное или отрицательное
- Чётное или нечётное
- Привидение к типу
- Преобразование в целое число
- Преобразование в число с плавающей точкой
- Округление
- Округление до целого числа в меньшую сторону:
- Округление до целого числа в большую сторону:
- Ведущие нули
- Добавить ведущие нули:
- Удалить ведущие нули:
- Абсолютное значение
- Сделать число отрицательным:
- Инкремент и декремент
- Минимальное значение
- Математические функции
Работа с числами в PHP
Сборник математических функций PHP и примеры их использования.
Проверка переменных
Является ли переменная числом
is_numeric($value) – проверяет, является ли значение или переменная числом или строкой, содержащей число.
is_numeric(1); // true is_numeric(0.1); // true is_numeric(-1); // true is_numeric(-0.1); // true is_numeric('1'); // true is_numeric('1abc'); // false is_numeric('abc'); // false
ctype_digit($value) – проверяет, являются ли все символы в строке цифрами.
ctype_digit('123'); // true ctype_digit('123.10'); // false ctype_digit('abc'); // false ctype_digit('1abc'); // false ctype_digit('abc1'); // false
is_int($value) – проверяет, является ли значение целым числом.
is_int(1); // true is_int(0.1); // false is_int(-1); // true is_int(-0.1); // false is_int('1'); // false is_int('1abc'); // false is_int('abc'); // false
is_float($value) – проверяет, является ли значение числом с плавающей точкой.
is_float(1); // false is_float(0.1); // true is_float(-1); // false is_float(-0.1); // true is_float('1'); // false is_float('1abc'); // false is_float('abc'); // false
Целое или число с плавающей точкой
Следующий пример определяет является ли число целым или с плавающей точкой, при этом не проверяет его отрицательность.
$value = 1; if (is_int($value)) < echo 'Целое число'; >elseif (is_float($value)) < echo 'Число с плавающей точкой'; >else
Положительное или отрицательное
$value = 1; if ($value == abs($value)) < echo 'Число положительное'; >if ($value != abs($value))
Чётное или нечётное
$value = 100; if (($value % 2) == 0) < echo 'Число чётное'; >if (($value % 2) != 0)
Привидение к типу
Преобразование в целое число
(int) 1; // 1 (int) 0.1; // 0 (int) -1; // -1 (int) -0.1; // 0 (int) '1'; // 1 (int) 'abc'; // 0 (int) '1abc'; // 1 (int) 'abc1'; // 0
В место (int) можно использовать (intiger) . Тоже самое делает функция intval() :
intval(1); // 1 intval(0.1); // 0 intval(-1); // -1 intval(-0.1); // 0 intval('1'); // 1 intval('abc'); // 0 intval('1abc'); // 1 intval('abc1'); // 0
Преобразование в число с плавающей точкой
(float) 1; // 1 (float) 0.1; // 0.1 (float) -1; // -1 (float) -0.1; // -0.1 (float) '1'; // 1 (float) 'abc'; // 0 (float) '1abc'; // 1 (float) 'abc1'; // 0
В место (float) можно использовать (double) или (real) и тоже самое делает функция floatval() .
floatval(1); // 1 floatval(0.1); // 0.1 floatval(-1); // -1 floatval(-0.1); // -0.1 floatval('1'); // 1 floatval('abc'); // 0 floatval('1abc'); // 1 floatval('abc1'); // 0
Округление
Функция round($value, $precision) округляет значение до указанных цифр после запятой.
echo round(100001.123456, 2); // 100001.12
Функция может окрукруглять значение целой части (числа перед запятой), для этого нужно указать отрицательное значение во втором аргументе.
Округление до целого числа в меньшую сторону:
echo floor(100.4); // 100 echo floor(100.9); // 100
Округление до целого числа в большую сторону:
echo ceil(100.4); // 101 echo ceil(100.1); // 101
Ведущие нули
Добавить ведущие нули:
echo sprintf("%06d", 100); // 000100 echo sprintf("%010d", 100); // 0000000100
Удалить ведущие нули:
echo intval('0000000100'); // 100 // Или с помощью ltrim echo ltrim('0000000100', '0'); // 100
Абсолютное значение
Функция abs($value) – возвращает абсолютное значение (модуль числа), т.е. из отрицательного делает положительное.
echo abs(100); // 100 echo abs(-100); // 100 echo abs(1.5); // 1.5 echo abs(-1.5); // 1.5
Сделать число отрицательным:
$value = 10; $value = -abs($value); echo $value; // -10
Инкремент и декремент
Инкремент – увеличение значения на единицу, бывает постфиксный и префиксный.
// Постфиксный инкремент $value = 10; echo $value++; // 10 echo $value; // 11 // Префиксный инкремент $value = 10; echo ++$value; // 11 echo $value; // 11
Декремент уменьшает значение на единицу.
// Постфиксный декремент $value = 10; echo $value--; // 10 echo $value; // 9 // Префиксный декремент $value = 10; echo --$value; // 9 echo $value; // 9
Минимальное значение
Математические функции
For people interest in Differential Equations, I’ve done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.
In the code there is one thing missing: the $string is often going outOfBound (Uninitialized string offset: 6 in. )
if your error setting is set a little too high. I just dont know how to fix this.
So there is the code for differential equation with (+ and -) only:
function differentiel($equa)
$equa = strtolower($equa);
echo «Equation de depart: «.$equa.»
«;
$final = «»;
I know this is not optimal but i’ve done this quick 🙂
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon.
Patoff
Wouldn’t the following function do the same but a lot easier than the one in the comment before?
function trimInteger($targetNumber,$newLength) return $targetNumber%pow(10,$newLength);
>
If you’re an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.
$windcorrection = rad2deg(asin((($windspeed * (sin(deg2rad($tt — ($winddirection-180))))/$tas))));
$groundspeed = $tas*cos(deg2rad($windcorrection)) + $windspeed*cos(deg2rad($tt-($winddirection-180)));
You can probably write these lines more beautiful, but they work!
If you need to deal with polar co-ordinates for somereason you will need to convert to and from x,y for input and output in most situations: here are some functions to convert cartesian to polar and polar to cartesian
//returns array of r, theta in the range of 0-2*pi (in radians)
function rect2polar($x,$y)
if(is_numeric($x)&&is_numeric($y))
$r=sqrt(pow($x,2)+pow($y,2));
if($x==0)
if($y>0) $theta=pi()/2;
else $theta=3*pi()/2;
>
else if($x <0) $theta=atan($y/$x)+pi();
else if($y <0) $theta=atan($y/$x)+2*pi();
else $theta=atan($y/$x);
$polar=array(«r»=>$r,»theta»=>$theta);
return $polar;
>
else return false;
>
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.
Another ordinal method, which does not involve utilizing date functions:
sprintf ( «%d%s» , $t , array_pop ( array_slice ( array_merge ( array( «th» , «st» , «nd» , «rd» ), array_fill ( 4 , 6 , «th» )), $t % 10 , 1 ))); ‘
?>
//had a mistake in last post, heres the corrected version
/*
Just a simple function to trim digits from the left side of an integer. TRIM DOWN TO 4-> (ie. 987654 => 7654)
*/
$s = ($targetNumber/ $digits); //make the last X digits the decimal part
$t = floor($targetNumber / $digits); //drop the last X digits (the decimal part)
$h = $s — $t; //remove all but the decimal part
$newInteger = ($h*$digits); //make the everything after the decimal point the new number
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:
// 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!)
// calculates the binomial coefficient «n over k» of 2 positive int values
// for 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 ));
>
I think, this is the optimal code for calculating factorials:
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:
function fib ( $int ) static $fibTable =array();
return empty( $fibTable [ $int ])? $fibTable [ $int ] = $int > 1 ? fib ( $int — 2 )+ fib ( $int — 1 ): 1 : $fibTable [ $int ];
>;
?>
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 );
>
?>
Here are are a nPr and a nPc function
(had to define NaN — don’t know, how to this the «rigth» way)
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 ;
>
?>
Another simpler function to check a number with the luhn algorithm :
function luhn ( $num ) <
if(! $num )
return false ;
$num = array_reverse ( str_split ( $num ));
$add = 0 ;
foreach( $num as $k => $v ) <
if( $k % 2 )
$v = $v * 2 ;
$add += ( $v >= 10 ? $v — 9 : $v );
>
return ( $add % 10 == 0 );
>
?>
Don’t know if foreach and arrays operations are faster than while and substr, but I feel it clearer.
This code will convert a decimal to it’s fraction equivalent. The precision can be set by changing PRECISION.
$count = 0 ;
$result =array();
decimalToFraction ( $_REQUEST [ ‘dec’ ], $count ,& $result );
$count = count ( $result );
$simp_fract = simplifyFraction ( $result , $count , 1 , $result [ $count ]);
/*
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 $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 » $bottom / $top » ;
>
>
?>
Here’s a simple way way to convert a number to an ordinal number I created:
$i == the number to convert. Put this inside a for loop if you need to populate an array.
// change increment variable to ordinal number.
$n1 = $i % 100 ; //first remove all but the last two digits
//$n is now used to determine the suffix.
$ord = ( $n2 == 1 ? $i . ‘st’ : ( ( $n2 == 2 ? $i . ‘nd’ : ( $n2 == 3 ? $i . ‘rd’ : $i . ‘th’ ) ) ) )
?>
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
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’ );
>
>
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.
while joogat’s one line function is short, it is probably better to calculate factorial iteratively instead of recursively. keep in mind if you want large factorials, you’ll need to use some sort of arbitrary precision integer or perhaps the BCMath functions. then again, unless you’re trying to do large numbers (170! is the highest that you can do that does not return infinity) you probably won’t notice any time difference.
function factorial ( $in ) // 0! = 1! = 1
$out = 1 ;
// Only if $in is >= 2
for ( $i = 2 ; $i $out *= $i ;
>
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 ;
>