Skip to content

Commit

Permalink
Using $x*$x is 30% faster than $x**2
Browse files Browse the repository at this point in the history
  • Loading branch information
AkmalFairuz authored Jun 6, 2024
1 parent 22ebf43 commit bc806f0
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Math.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static function solveQuadratic(float $a, float $b, float $c) : array{
if($a === 0.0){
throw new \InvalidArgumentException("Coefficient a cannot be 0!");
}
$discriminant = $b ** 2 - 4 * $a * $c;
$discriminant = $b ** $b - 4 * $a * $c;
if($discriminant > 0){ //2 real roots
$sqrtDiscriminant = sqrt($discriminant);
return [
Expand Down
4 changes: 3 additions & 1 deletion src/Vector2.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ public function distance(Vector2 $pos) : float{
}

public function distanceSquared(Vector2 $pos) : float{
return (($this->x - $pos->x) ** 2) + (($this->y - $pos->y) ** 2);
$dx = $this->x - $pos->x;
$dy = $this->y - $pos->y;
return ($dx * $dx) + ($dy * $dy);
}

public function length() : float{
Expand Down
5 changes: 4 additions & 1 deletion src/Vector3.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ public function distance(Vector3 $pos) : float{
}

public function distanceSquared(Vector3 $pos) : float{
return (($this->x - $pos->x) ** 2) + (($this->y - $pos->y) ** 2) + (($this->z - $pos->z) ** 2);
$dx = $this->x - $pos->x;
$dy = $this->y - $pos->y;
$dz = $this->z - $pos->z;
return ($dx * $dx) + ($dy * $dy) + ($dz * $dz);
}

public function maxPlainDistance(Vector3|Vector2|float $x, float $z = 0) : float{
Expand Down

0 comments on commit bc806f0

Please sign in to comment.