In PHP by using MathPHP, you can easily apply scalar operations to vectors, perform trigonometric computations, and manipulate scalars in a structured way, making mathematical programming in PHP more convenient and reliable.
Example of Use:
Example with MathPHP
useMathPHP\Arithmetic;useMathPHP\Exception\BadParameterException;echo"Arithmetic Operations in MathPHP\n";echo"---------------------------------\n";// Example 1: Nth Root Calculation$x =27;$n =3;echo"Cube Root of $x: ".Arithmetic::root($x, $n)."\n";// Example 2: Cube Root$x =-27;echo"Cube Root of $x: ".Arithmetic::cubeRoot($x)."\n";// Example 3: Integer Square Roottry { $x =17;echo"Integer Square Root of $x: ".Arithmetic::isqrt($x)."\n";} catch (BadParameterException $e) {echo"Error: ". $e->getMessage()."\n";}// Example 4: Digit Sum$x =5031;echo"Digit Sum of $x: ".Arithmetic::digitSum($x)."\n";// Example 5: Digital Root$x =65536;echo"Digital Root of $x: ".Arithmetic::digitalRoot($x)."\n";// Example 6: Almost Equal$a =1.00000000001;$b =1.00000000002;echo"Are $a and $b almost equal? ". (Arithmetic::almostEqual($a, $b)?"Yes":"No") ."\n";// Example 7: Copy Sign$magnitude =5.5;$sign =-3;echo"Copy sign of $sign to $magnitude: ".Arithmetic::copySign($magnitude, $sign)."\n";// Example 8: Modulo Operation$a =-13;$n =5;echo"Modulo of $a % $n: ".Arithmetic::modulo($a, $n)."\n";
Scalar Operations with Pure PHP
In PHP it can be written as a class Scalar with implementation of a set of scalar operations.
This class is a PHP implementation of scalar operations commonly used in linear algebra and, by extension, in various AI and machine learning algorithms. It provides a robust set of methods for performing vectors calculations, making it a valuable tool for developers working on AI projects in PHP.
Example of Class Scalar
namespaceApphp\MLKit\Math\Linear;useDivisionByZeroError;useInvalidArgumentException;useRandom\RandomException;/** * Scalar class provides a comprehensive set of mathematical operations for scalar values * * This class includes basic arithmetic operations, scalar-vector operations, * mathematical functions, trigonometric operations, random number generation, * comparison operations, and bitwise operations. All methods are static and * designed for high precision mathematical computations. * * @package Apphp\MLKit\Math\Linear */classScalar {/** * Default precision settings for different operation types * @vararray<string, int> */privatestaticarray $defaultPrecisions = ['basic_arithmetic'=>5,// Basic arithmetic operations'exponential'=>8,// Exponential and logarithmic operations'trigonometric'=>8,// Trigonometric functions'vector'=>6,// Vector operations ];/** * Custom precision settings that override defaults * @vararray<string, int> */privatestaticarray $customPrecisions = [];/** * Global precision setting that overrides all others when set * @varint|null */privatestatic?int $globalPrecision =null;/** * Sets the global precision for all operations * * @paramint $precision Number of decimal places * @returnvoid * @throwsInvalidArgumentException */publicstaticfunctionsetPrecision(int $precision):void {if ($precision <0) {thrownewInvalidArgumentException("Precision must be non-negative. Got: {$precision}"); }self::$globalPrecision= $precision; }/** * Sets precision for a specific operation type * * @paramstring $operation Operation type ('basic_arithmetic', 'trigonometric', 'exponential', 'vector') * @paramint $precision Number of decimal places * @returnvoid * @throwsInvalidArgumentException */publicstaticfunctionsetOperationPrecision(string $operation,int $precision):void {if ($precision <0) {thrownewInvalidArgumentException("Precision must be non-negative. Got: {$precision}"); }if (!isset(self::$defaultPrecisions[$operation])) {thrownewInvalidArgumentException("Invalid operation type: {$operation}"); }self::$customPrecisions[$operation] = $precision; }/** * Resets all precision settings to defaults * * @returnvoid */publicstaticfunctionresetPrecision():void {self::$globalPrecision=null;self::$customPrecisions= []; }/** * Gets the current global precision setting * * @returnint|null Current global precision or null if not set */publicstaticfunctiongetPrecision():?int {returnself::$globalPrecision; }/** * Gets the current precision for a specific operation type * * @paramstring $operation Operation type * @returnint Current precision for the operation * @throwsInvalidArgumentException */publicstaticfunctiongetOperationPrecision(string $operation):int {returnself::getOptimalPrecision($operation); }/** * Gets the optimal precision for a given operation * * @paramstring $operation Type of operation ('basic_arithmetic', 'trigonometric', 'exponential', 'vector') * @paramint|null $precision Optional precision override * @returnint Optimal precision for the operation * @throwsInvalidArgumentException */privatestaticfunctiongetOptimalPrecision(string $operation,?int $precision =null):int {// Method-specific precision has highest priorityif ($precision !==null) {if ($precision <0) {thrownewInvalidArgumentException("Precision must be non-negative. Got: {$precision}"); }return $precision; }// Custom operation-specific precision has second priorityif (isset(self::$customPrecisions[$operation])) {returnself::$customPrecisions[$operation]; }// Global precision overrides defaults if setif (self::$globalPrecision!==null) {returnself::$globalPrecision; }// Default precision for operation typeif (isset(self::$defaultPrecisions[$operation])) {returnself::$defaultPrecisions[$operation]; }thrownewInvalidArgumentException("Invalid operation type: {$operation}"); }/** * Adds two numbers * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @paramint|null $precision Number of decimal places to round to * @returnfloat Sum of the two numbers */publicstaticfunctionadd(float|int $a,float|int $b,?int $precision =null):float { $precision =self::getOptimalPrecision('basic_arithmetic', $precision);returnround($a + $b, $precision); }/** * Subtracts second number from the first * * @paramfloat|int $a Number to subtract from * @paramfloat|int $b Number to subtract * @paramint|null $precision Number of decimal places to round to * @returnfloat Result of subtraction */publicstaticfunctionsubtract(float|int $a,float|int $b,?int $precision =null):float { $precision =self::getOptimalPrecision('basic_arithmetic', $precision);returnround($a - $b, $precision); }/** * Multiplies two numbers * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @paramint|null $precision Number of decimal places to round to * @returnfloat Product of the two numbers */publicstaticfunctionmultiply(float|int $a,float|int $b,?int $precision =null):float { $precision =self::getOptimalPrecision('basic_arithmetic', $precision);returnround($a * $b, $precision); }/** * Divides first number by the second * * @paramfloat|int $a Dividend * @paramfloat|int $b Divisor * @paramint|null $precision Number of decimal places to round to * @returnfloat|string Result of division or 'undefined' if divisor is zero * @throwsDivisionByZeroError */publicstaticfunctiondivide(float|int $a,float|int $b,?int $precision =null):float|string {if ($b ===0) {thrownewDivisionByZeroError('Division by zero is not allowed'); } $precision =self::getOptimalPrecision('basic_arithmetic', $precision);returnround($a / $b, $precision); }/** * Calculates the floating-point remainder (modulo) * * @paramfloat|int $a Dividend * @paramfloat|int $b Divisor * @paramint|null $precision Number of decimal places to round to * @returnfloat Remainder of the division * @throwsDivisionByZeroError */publicstaticfunctionmodulus(float|int $a,float|int $b,?int $precision =null):float {if ($b ===0) {thrownewDivisionByZeroError('Division by zero is not allowed'); } $precision =self::getOptimalPrecision('basic_arithmetic', $precision);returnround(fmod($a, $b), $precision); }/** * Raises first number to the power of second number * * @paramfloat|int $a Base number * @paramfloat|int $b Exponent * @paramint|null $precision Number of decimal places to round to * @returnfloat Result of exponentiation */publicstaticfunctionpower(float|int $a,float|int $b,?int $precision =null):float { $precision =self::getOptimalPrecision('exponential', $precision);returnround($a ** $b, $precision); }/** * Multiplies each element of a vector by a scalar value * * @paramfloat|int $scalar The scalar value to multiply by * @paramarray<int|float> $vector Array of numbers * @paramint|null $precision Number of decimal places to round to * @returnarray<int|float> Resulting vector after multiplication */publicstaticfunctionmultiplyVector(float|int $scalar,array $vector,?int $precision =null):array { $precision =self::getOptimalPrecision('vector', $precision);returnarray_map(fn ($x) => round($x * $scalar, $precision), $vector); }/** * Adds a scalar value to each element of a vector * * @paramfloat|int $scalar The scalar value to add * @paramarray<int|float> $vector Array of numbers * @paramint|null $precision Number of decimal places to round to * @returnarray<int|float> Resulting vector after addition */publicstaticfunctionaddToVector(float|int $scalar,array $vector,?int $precision =null):array { $precision =self::getOptimalPrecision('vector', $precision);returnarray_map(fn ($x) => round($x + $scalar, $precision), $vector); }/** * Calculates the absolute value of a number * * @paramfloat|int $x Input number * @returnfloat Absolute value */publicstaticfunctionabsolute(float|int $x):float {returnabs($x); }/** * Rounds a number up to the next highest integer * * @paramfloat|int $x Input number * @returnfloat Ceiling value */publicstaticfunctionceiling(float|int $x):float {returnceil($x); }/** * Rounds a number down to the next lowest integer * * @paramfloat|int $x Input number * @returnfloat Floor value */publicstaticfunctionfloor(float|int $x):float {returnfloor($x); }/** * Rounds a number to the nearest integer * * @paramfloat|int $x Input number * @returnfloat Rounded value */publicstaticfunctionround(float|int $x):float {returnround($x); }/** * Calculates e raised to the power of x * * @paramfloat|int $x The exponent * @paramint|null $precision Number of decimal places to round to * @returnfloat e^x */publicstaticfunctionexponential(float|int $x,?int $precision =null):float { $precision =self::getOptimalPrecision('exponential', $precision);returnround(exp($x), $precision); }/** * Calculates the natural logarithm of a number * * @paramfloat|int $x Input number (must be positive) * @paramint|null $precision Number of decimal places to round to * @returnfloat|string Natural logarithm or 'undefined' if x <= 0 * @throwsInvalidArgumentException */publicstaticfunctionlogarithm(float|int $x,?int $precision =null):float|string {if ($x <=0) {thrownewInvalidArgumentException("Logarithm argument must be positive. Got: {$x}"); } $precision =self::getOptimalPrecision('exponential', $precision);returnround(log($x), $precision); }/** * Calculates the square root of the absolute value of a number * * @paramfloat|int $x Input number * @paramint|null $precision Number of decimal places to round to * @returnfloat Square root of |x| * @throwsInvalidArgumentException */publicstaticfunctionsquareRoot(float|int $x,?int $precision =null):float {if ($x <0) {thrownewInvalidArgumentException("Square root argument must be non-negative. Got: {$x}"); } $precision =self::getOptimalPrecision('exponential', $precision);returnround(sqrt(abs($x)), $precision); }/** * Calculates the sine of an angle * * @paramfloat|int $angle Angle in radians * @paramint|null $precision Number of decimal places to round to * @returnfloat Sine value */publicstaticfunctionsine(float|int $angle,?int $precision =null):float { $precision =self::getOptimalPrecision('trigonometric', $precision);returnround(sin($angle), $precision); }/** * Calculates the cosine of an angle * * @paramfloat|int $angle Angle in radians * @paramint|null $precision Number of decimal places to round to * @returnfloat Cosine value */publicstaticfunctioncosine(float|int $angle,?int $precision =null):float { $precision =self::getOptimalPrecision('trigonometric', $precision);returnround(cos($angle), $precision); }/** * Calculates the tangent of an angle * * @paramfloat|int $angle Angle in radians * @paramint|null $precision Number of decimal places to round to * @returnfloat|string Returns 'undefined' for angles where tangent is undefined (π/2 + nπ) */publicstaticfunctiontangent(float|int $angle,?int $precision =null):float|string {// Check if angle is π/2 + nπ where tangent is undefined $normalized =fmod($angle,M_PI); // Normalize to [0, π]if (abs($normalized -M_PI_2)<0.00000001) {return'undefined'; } $precision =self::getOptimalPrecision('trigonometric', $precision);returnround(tan($angle), $precision); }/** * Generates a random integer within specified range * * @paramint $min Lower bound (inclusive) * @paramint $max Upper bound (inclusive) * @returnint Random integer * @throwsRandomException */publicstaticfunctionrandomInt(int $min =1,int $max =10):int {returnrandom_int($min, $max); }/** * Generates a random integer using Mersenne Twister algorithm * * @paramint $min Lower bound (inclusive) * @paramint $max Upper bound (inclusive) * @returnint Random integer */publicstaticfunctionmtRandomInt(int $min =1,int $max =10):int {returnmt_rand($min, $max); }/** * Generates a random float between 0 and 1 using combined linear congruential generator * * @returnfloat Random float between 0 and 1 */publicstaticfunctionlcgValue():float {returnlcg_value(); }/** * Checks if first number is greater than second * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a > b, false otherwise */publicstaticfunctionisGreaterThan(float|int $a,float|int $b):bool {return $a > $b; }/** * Checks if first number is less than second * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a < b, false otherwise */publicstaticfunctionisLessThan(float|int $a,float|int $b):bool {return $a < $b; }/** * Checks if two numbers are equal * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a == b, false otherwise */publicstaticfunctionisEqual(float|int $a,float|int $b):bool {return $a == $b; }/** * Checks if two numbers are not equal * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a != b, false otherwise */publicstaticfunctionisNotEqual(float|int $a,float|int $b):bool {return $a != $b; }/** * Checks if first number is greater than or equal to second * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a >= b, false otherwise */publicstaticfunctionisGreaterOrEqual(float|int $a,float|int $b):bool {return $a >= $b; }/** * Checks if first number is less than or equal to second * * @paramfloat|int $a First number * @paramfloat|int $b Second number * @returnbool True if a <= b, false otherwise */publicstaticfunctionisLessOrEqual(float|int $a,float|int $b):bool {return $a <= $b; }/** * Performs bitwise AND operation * * @paramint $a First integer * @paramint $b Second integer * @returnint Result of bitwise AND */publicstaticfunctionbitwiseAnd(int $a,int $b):int {return $a & $b; }/** * Performs bitwise OR operation * * @paramint $a First integer * @paramint $b Second integer * @returnint Result of bitwise OR */publicstaticfunctionbitwiseOr(int $a,int $b):int {return $a | $b; }/** * Performs bitwise XOR operation * * @paramint $a First integer * @paramint $b Second integer * @returnint Result of bitwise XOR */publicstaticfunctionbitwiseXor(int $a,int $b):int {return $a ^ $b; }/** * Performs bitwise NOT operation * * @paramint $a Input integer * @returnint Result of bitwise NOT */publicstaticfunctionbitwiseNot(int $a):int {return~$a; }/** * Performs left shift operation * * @paramint $a Number to shift * @paramint $positions Number of positions to shift * @returnint Result after left shift * @throwsInvalidArgumentException */publicstaticfunctionleftShift(int $a,int $positions =1):int {if ($positions <0) {thrownewInvalidArgumentException("Shift amount must be non-negative. Got: {$positions}"); }return $a << $positions; }/** * Performs right shift operation * * @paramint $a Number to shift * @paramint $positions Number of positions to shift * @returnint Result after right shift * @throwsInvalidArgumentException */publicstaticfunctionrightShift(int $a,int $positions =1):int {if ($positions <0) {thrownewInvalidArgumentException("Shift amount must be non-negative. Got: {$positions}"); }return $a >> $positions; }}