Проверка на остаток php

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

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:

Читайте также:  Difference between list and array python

// 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 ]);

Читайте также:  Using and in if condition in java

/*
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.

Читайте также:  View objects in python

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

if ( $r < 2 )
$r = 1 ;
else <
for ( $i = $r — 1 ; $i > 1 ; $i — )
$r = $r * $i ;
>

Источник

Проверка на остаток php

Помните школьные основы арифметики? Описанные ниже операторы работают так же.

Арифметические операции

Пример Название Результат
+$a Идентичность Конвертация $a в int или float , что более подходит.
-$a Отрицание Смена знака $a .
$a + $b Сложение Сумма $a и $b .
$a — $b Вычитание Разность $a и $b .
$a * $b Умножение Произведение $a и $b .
$a / $b Деление Частное от деления $a на $b .
$a % $b Деление по модулю Целочисленный остаток от деления $a на $b .
$a ** $b Возведение в степень Возведение $a в степень $b .

Операция деления («/») возвращает число с плавающей точкой, кроме случая, когда оба значения являются целыми числами (или строками, которые преобразуются в целые числа), которые делятся нацело — в этом случае возвращается целое значение. Для целочисленного деления используйте intdiv() .

При делении по модулю операнды преобразуются в целые числа ( int ) (путём удаления дробной части) до начала операции. Для деления по модулю чисел с плавающей точкой используйте fmod() .

Результат операции остатка от деления % будет иметь тот же знак, что и делимое — то есть, результат $a % $b будет иметь тот же знак, что и $a . Например:

echo ( 5 % 3 ). «\n» ; // выводит 2
echo ( 5 % — 3 ). «\n» ; // выводит 2
echo (- 5 % 3 ). «\n» ; // выводит -2
echo (- 5 % — 3 ). «\n» ; // выводит -2

Источник

Деление без остатка (PHP)

Чтобы проверить делится одно целочисленное число, на другое целочисленное число без остатка понадобится деление по модулю.

Деление по модулю

В PHP деление по модулю, осуществляется символом % (процент). Результатом выполнения этой арифметической операции является остаток от деления.

Пример

Нужно проверить несколько чисел на возможность деления без остатка.

else < echo 'Числа делятся с остатком'; >$num1 = 8; $num2 = 2; echo $num1 % $num2 == 0 ? // 8%2=0 ‘Числа делятся без остатка’ : ‘Числа делятся с остатком’; // true $num1 = 9; $num2 = 4; echo $num1 % $num2 == 0 ? // 9%4=1 ‘Числа делятся без остатка’ : ‘Числа делятся с остатком’; // false $num1 = 16; $num2 = 4; echo $num1 % $num2 == 0 ? // 16%4=0 ‘Числа делятся без остатка’ : ‘Числа делятся с остатком’; // true $num1 = 18; $num2 = 7; echo $num1 % $num2 == 0 ? // 18%7=4 ‘Числа делятся без остатка’ : ‘Числа делятся с остатком’; // false ?>

Категории

Читайте также

  • Деление без остатка (JavaScript)
  • Вывод ip2long чисел (PHP)
  • Первые N символов строки цифры (PHP)
  • Переменная является числом (PHP)
  • Сделать число отрицательным (PHP)
  • Загрузка изображений без перезагрузки страницы
  • Singleton Trait (PHP)
  • Редирект (PHP)
  • Склонение числительных на PHP
  • Транслит (PHP)
  • Проверка электронной почты (PHP)
  • Включить-отключить вывод ошибок (PHP)

Источник

Оцените статью