Search code examples
math3dgeometry

Calculate Volume of any Tetrahedron given 4 points


I need to calculate the volume of a tetrahedron given the coordinates of its four corner points.


Solution

  • Here is the code, in PHP, that calculates the Volume of any Tetrahedron given 4 points:

    class Math{
    public static function determinant(array $vals){
        $s = sizeof($vals);
        $sum = 0.0;
        for( $i=0; $i < $s ; $i++ ){
            $mult = 1.0;
            for($j=0; $j < $s ; $j++ ){
                $mult *= $vals[$j][ ($i+$j)%$s ];
            }
            $sum += $mult;
        }
        for( $i=0; $i < $s ; $i++ ){
            $mult = 1;
            for($j=0; $j < $s ; $j++ ){
                $mult *= $vals[$j][ ($i-$j < 0? $s - ($j-$i) :($i-$j)) ];
            }
            $sum -= $mult;
        }
        return $sum;
    }
    
    public static function subtract(array $a, array $b){
        for($i = 0; $i < sizeof($a); $i++)
            $a[$i] -= $b[$i];
    
        return $a;
    }
    }
    // TEST CASE
    $a = array(0,0,0);
    $d = array(2,0,0);
    $c = array(0,2,0);
    $b = array(0,0,2);
    
    echo abs(Math::determinant(array(
    Math::subtract($a, $b),
    Math::subtract($b, $c),
    Math::subtract($c, $d),
    )))/6;