Calculate Volume of any Tetrahedron given 4 points - math

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

Say if you have 4 vertices a,b,c,d (3-D vectors).
Now, the problem comes down to writing code which solves cross product and dot product of vectors. If you are from python, you can use NumPy or else you can write code on your own.
The Wikipedia link should definitely help you. LINK

One way to compute this volume is this:
1 [ax bx cx dx]
V = --- det [ay by cy dy]
6 [az bz cz dz]
[ 1 1 1 1]
This involves the evaluation of a 4×4 determinant. It generalizes nicely to simplices of higher dimensions, with the 6 being a special case of n!, the factorial of the dimension. The resulting volume will be oriented, i.e. may be negative depending on the order of points. If you don't want that, take the absolute value of the result.
If you have a math library at hand, the above formulation might be among the easiest to write down, and the software can take it from there. If not, you might simplify things first by subtracting the d coordinates from a through c. This will not change the volume but turn the rightmost column into (0, 0, 0, 1). As a result, you can compute the value of the matrix simply as the determinant of the upper left 3×3 submatrix. And using the equation
det(a, b, c) = a · (b × c)
you end up with the formula from Surya's answer.
In case you don't have coordinates for the points, but just distances between them, look at Tartaglia's Formula which is essentually a squared version of the above, although it's not as straight-forward as it would seem at first glance.

Ivan Seidel's example, in Python (answer is 1.3333...)
def determinant_3x3(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) -
m[1][0] * (m[0][1] * m[2][2] - m[0][2] * m[2][1]) +
m[2][0] * (m[0][1] * m[1][2] - m[0][2] * m[1][1]))
def subtract(a, b):
return (a[0] - b[0],
a[1] - b[1],
a[2] - b[2])
def tetrahedron_calc_volume(a, b, c, d):
return (abs(determinant_3x3((subtract(a, b),
subtract(b, c),
subtract(c, d),
))) / 6.0)
a = [0.0, 0.0, 0.0]
d = [2.0, 0.0, 0.0]
c = [0.0, 2.0, 0.0]
b = [0.0, 0.0, 2.0]
print(tetrahedron_calc_volume(a, b, c, d))

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;

Related

solving matrices using Cramer's rule

So I searched the in internet looking for programs with Cramer's Rule and there were some few, but apparently these examples were for fixed matrices only like 2x2 or 4x4.
However, I am looking for a way to solve a NxN Matrix. So I started and reached the point of asking the user for the size of the matrix and asked the user to input the values of the matrix but then I don't know how to move on from here.
As in I guess my next step is to apply Cramer's rule and get the answers but I just don't know how.This is the step I'm missing. can anybody help me please?
First, you need to calculate the determinant of your equations system matrix - that is the matrix, that consists of the coefficients (from the left-hand side of the equations) - let it be D.
Then, to calculate the value of a certain variable, you need to take the matrix of your system (from the previous step), replace the coefficients of the corresponding column with constant terms (from the right-hand side), calculate the determinant of resulting matrix - let it be C, and divide C by D.
A bit more about the replacement from the previous step: say, your matrix if 3x3 (as in the image) - so, you have a system of equations, where every a coefficient is multiplied by x, every b - by y, and every c by z, and ds are the constant terms. So, to calculate y, you replace those coefficients that are multiplied by y - bs in this case, with ds.
You perform the second step for every variable and your system gets solved.
You can find an example in https://rosettacode.org/wiki/Cramer%27s_rule#C
Although the specific example deals with a 4X4 matrix the code is written to accommodate any size square matrix.
What you need is calculate the determinant. Cramer's rule is just for the determinant of a NxN matrix
if N is not big, you can use the Cramer's rule(see code below), which is quite straightforward. However, this method is not efficient; if your N is big, you need to resort to other methods, such as lu decomposition
Assuming your data is double, and result can be hold by double.
#include <malloc.h>
#include <stdio.h>
double det(double * matrix, int n) {
if( 1 >= n ) return matrix[ 0 ];
double *subMatrix = (double*)malloc(( n - 1 )*( n - 1 ) * sizeof(double));
double result = 0.0;
for( int i = 0; i < n; ++i ) {
for( int j = 0; j < n - 1; ++j ) {
for( int k = 0; k < i; ++k )
subMatrix[ j*( n - 1 ) + k ] = matrix[ ( j + 1 )*n + k ];
for( int k = i + 1; k < n; ++k )
subMatrix[ j*( n - 1 ) + ( k - 1 ) ] = matrix[ ( j + 1 )*n + k ];
}
if( i % 2 == 0 )
result += matrix[ 0 * n + i ] * det(subMatrix, n - 1);
else
result -= matrix[ 0 * n + i ] * det(subMatrix, n - 1);
}
free(subMatrix);
return result;
}
int main() {
double matrix[ ] = { 1,2,3,4,5,6,7,8,2,6,4,8,3,1,1,2 };
printf("%lf\n", det(matrix, 4));
return 0;
}

Complexity of recursive algorithm, that finds largest element in an array

How to calculate complexity of ths recursive algorithm?
int findMax(int a[ ], int l, int r)
{
if (r – l == 1)
return a[ l ];
int m = ( l + r ) / 2;
int u = findMax(a, l, m);
int v = findMax(a, m, r);
if (u > v)
return u;
else
return v;
}
From the Master Theorem:
T(n) = a * T(n/b) + f(n)
Where:
a is number of sub-problems
f(n) is cost of operation outside the recursion; f(n) = O(nc)
n/b size of the sub-problem
The idea behind this function is that you repeat the operation on the first half of items (T(n/2)) and on the second half of items (T(n/2)). You get the results and compare them (O(1)) so you have:
T(n) = 2 * T(n/2) + O(1)
So f(n) = O(1) and in terms of n value we get O(n0) - we need that to calculate c. So a = 2 and b = 2 and c = 0. From the Master Theorem (as correctly pointed out in comments) we end up with case where c < logba as log22 = 0. In this case the complexity of whole recursive call is O(n).

Two rectangles on a plane

In the last few days I try to solve this problem. I even have the solution but I can't figure it out. Can someone help me?
Here the problem:
You are given two rectangles on a plane.
The centers of both rectangles are located in the origin of coordinates
(meaning the center of the rectangle's symmetry).
The first rectangle's sides are parallel to the coordinate axes:
the length of the side that is parallel to the Ox axis, equals w,
the length of the side that is parallel to the Oy axis, equals h.
The second rectangle can be obtained by rotating the first rectangle
relative to the origin of coordinates by angle α.
Example:
http://i.imgur.com/qi1WQVq.png
Your task is to find the area of the region which belongs to both
given rectangles. This region is shaded in the picture.
Input
The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.
Output
In a single line print a real number — the area of the region which belongs to both given rectangles.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Sample test(s)
input
1 1 45
output
0.828427125
input
6 4 30
output
19.668384925
Here a possible implementation:
<?php
list($w, $h, $alphaInt) = explode(' ', '34989 23482 180');
if ($alphaInt == 0 || $alphaInt == 180) {
$res = $h * $w;
}
else if ($alphaInt == 90) {
$res = $h * $h;
}
else {
if ($alphaInt > 90) $alphaInt = 180 - $alphaInt;
$alpha = $alphaInt / 180.0 * M_PI;
//echo '$alpha:' . $alpha . "\n";
$cos = cos($alpha);
$sin = sin($alpha);
//echo '$cos: ' . $cos . "\n";
//echo '$sin: ' . $sin . "\n";
$c = $w / 2 * $cos + $h / 2 * $sin - $w / 2;
//echo '$c: ' . $c . "\n";
$r1 = $c / $cos;
$r2 = $c / $sin;
//echo '$r1: ' . $r1 . "\n";
//echo '$r2: ' . $r2 . "\n";
$c = $w / 2 * $sin + $h / 2 * $cos - $h / 2;
//echo '$c: ' . $c . "\n";
$r3 = $c / $cos;
$r4 = $c / $sin;
//echo '$r3: ' . $r3 . "\n";
//echo '$r4: ' . $r4 . "\n";
if ($r1 < 0 || $r2 < 0 || $r3 < 0 || $r4 < 0) {
$res = $h * $h / $sin; //$res = $w * $w / $cos;
}
else {
$res = $h * $w - $r1 * $r2 - $r3 * $r4;
}
}
echo '$res: ' . $res . "\n";
Small alpha
When w*sin(alpha) < h*(1+cos(alpha)) (i.e., before the vertices of the new rectangle meet the vertices of the old one for the first time), the area of the intersection is the area of the original rectangle (w * h) minus 4 triangles (2 pairs of identical ones). Let the bigger triangle have hypotenuse a and the smaller hypotenuse b, then the area is
A = w * h - a*a*cos(alpha)*sin(alpha) - b*b*cos(alpha)*sin(alpha)
The sides of the original rectangle satisfy a system of equations:
a + a * cos(alpha) + b * sin(alpha) = w
a * sin(alpha) + b + b * cos(alpha) = h
Using the half-angle formulas,
a * cos(alpha/2) + b * sin(alpha/2) = w/(2*cos(alpha/2))
a * sin(alpha/2) + b * cos(alpha/2) = h/(2*cos(alpha/2))
thus (the matrix on the LHS is a rotation!)
a^2 + b^2 = (w^2 + h^2) / (2*cos(alpha/2))^2
and
A = h * w - (w^2 + h^2) * cos(alpha)* sin(alpha) / (2*cos(alpha/2))^2
(this can be simplified further a little bit)
Bigger alpha
When alpha is bigger (but still alpha<pi/2), the intersection is a parallelogram (actually, a rhombus) whose 2 altitudes are h and 4 sides h/sin(alpha) and the area is, thus, h*h/sin(alpha) (yes, it does not depend on w!)
Other alpha
Use symmetry to reduce alpha to [0;pi/2] and use one of the two cases above.
You might try describing both rectangles as solutions to a system of four linear insqualities.
The set of points in their intersection is the set of solutions to both sets of linear inequalities.
You want the area of that set of solutions. You can find all points at which at least two of your eight inequalities are tight. Filter out those that don't satisfy all of the inequalities. Then take their convex hull using Graham's scan and compute the area using the surveyor's formula.
This method works to find the intersection of any two convex polygons. Slightly modified, it generalises (in the form of Fourier-Motzkin elimination and the double description method for computing the intersection and determinants for volume calculation) to convex polyhedra in any dimension.

Calculate bessel function in MATLAB using Jm+1=2mj(m) -j(m-1) formula

I tried to implement bessel function using that formula, this is the code:
function result=Bessel(num);
if num==0
result=bessel(0,1);
elseif num==1
result=bessel(1,1);
else
result=2*(num-1)*Bessel(num-1)-Bessel(num-2);
end;
But if I use MATLAB's bessel function to compare it with this one, I get too high different values.
For example if I type Bessel(20) it gives me 3.1689e+005 as result, if instead I type bessel(20,1) it gives me 3.8735e-025 , a totally different result.
such recurrence relations are nice in mathematics but numerically unstable when implementing algorithms using limited precision representations of floating-point numbers.
Consider the following comparison:
x = 0:20;
y1 = arrayfun(#(n)besselj(n,1), x); %# builtin function
y2 = arrayfun(#Bessel, x); %# your function
semilogy(x,y1, x,y2), grid on
legend('besselj','Bessel')
title('J_\nu(z)'), xlabel('\nu'), ylabel('log scale')
So you can see how the computed values start to differ significantly after 9.
According to MATLAB:
BESSELJ uses a MEX interface to a Fortran library by D. E. Amos.
and gives the following as references for their implementation:
D. E. Amos, "A subroutine package for Bessel functions of a complex
argument and nonnegative order", Sandia National Laboratory Report,
SAND85-1018, May, 1985.
D. E. Amos, "A portable package for Bessel functions of a complex
argument and nonnegative order", Trans. Math. Software, 1986.
The forward recurrence relation you are using is not stable. To see why, consider that the values of BesselJ(n,x) become smaller and smaller by about a factor 1/2n. You can see this by looking at the first term of the Taylor series for J.
So, what you're doing is subtracting a large number from a multiple of a somewhat smaller number to get an even smaller number. Numerically, that's not going to work well.
Look at it this way. We know the result is of the order of 10^-25. You start out with numbers that are of the order of 1. So in order to get even one accurate digit out of this, we have to know the first two numbers with at least 25 digits precision. We clearly don't, and the recurrence actually diverges.
Using the same recurrence relation to go backwards, from high orders to low orders, is stable. When you start with correct values for J(20,1) and J(19,1), you can calculate all orders down to 0 with full accuracy as well. Why does this work? Because now the numbers are getting larger in each step. You're subtracting a very small number from an exact multiple of a larger number to get an even larger number.
You can just modify the code below which is for the Spherical bessel function. It is well tested and works for all arguments and order range. I am sorry it is in C#
public static Complex bessel(int n, Complex z)
{
if (n == 0) return sin(z) / z;
if (n == 1) return sin(z) / (z * z) - cos(z) / z;
if (n <= System.Math.Abs(z.real))
{
Complex h0 = bessel(0, z);
Complex h1 = bessel(1, z);
Complex ret = 0;
for (int i = 2; i <= n; i++)
{
ret = (2 * i - 1) / z * h1 - h0;
h0 = h1;
h1 = ret;
if (double.IsInfinity(ret.real) || double.IsInfinity(ret.imag)) return double.PositiveInfinity;
}
return ret;
}
else
{
double u = 2.0 * abs(z.real) / (2 * n + 1);
double a = 0.1;
double b = 0.175;
int v = n - (int)System.Math.Ceiling((System.Math.Log(0.5e-16 * (a + b * u * (2 - System.Math.Pow(u, 2)) / (1 - System.Math.Pow(u, 2))), 2)));
Complex ret = 0;
while (v > n - 1)
{
ret = z / (2 * v + 1.0 - z * ret);
v = v - 1;
}
Complex jnM1 = ret;
while (v > 0)
{
ret = z / (2 * v + 1.0 - z * ret);
jnM1 = jnM1 * ret;
v = v - 1;
}
return jnM1 * sin(z) / z;
}
}

Math Problem: Scale a graph so that it matches another

I have 2 tables of values and want to scale the first one so that it matches the 2nd one as good as possible. Both have the same length. If both are drawn as graphs in a diagram they should be as close to each other as possible. But I do not want quadratic, but simple linear weights.
My problem is, that I have no idea how to actually compute the best scaling factor because of the Abs function.
Some pseudocode:
//given:
float[] table1= ...;
float[] table2= ...;
//wanted:
float factor= ???; // I have no idea how to compute this
float remainingDifference=0;
for(int i=0; i<length; i++)
{
float scaledValue=table1[i] * factor;
//Sum up the differences. I use the Abs function because negative differences are differences too.
remainingDifference += Abs(scaledValue - table2[i]);
}
I want to compute the scaling factor so that the remainingDifference is minimal.
Simple linear weights is hard like you said.
a_n = first sequence
b_n = second sequence
c = scaling factor
Your residual function is (sums are from i=1 to N, the number of points):
SUM( |a_i - c*b_i| )
Taking the derivative with respect to c yields:
d/dc SUM( |a_i - c*b_i| )
= SUM( b_i * (a_i - c*b_i)/|a_i - c*b_i| )
Setting to 0 and solving for c is hard. I don't think there's an analytic way of doing that. You may want to try https://math.stackexchange.com/ to see if they have any bright ideas.
However if you work with quadratic weights, it becomes significantly simpler:
d/dc SUM( (a_i - c*b_i)^2 )
= SUM( 2*(a_i - c*b_i)* -c )
= -2c * SUM( a_i - c*b_i ) = 0
=> SUM(a_i) - c*SUM(b_i) = 0
=> c = SUM(a_i) / SUM(b_i)
I strongly suggest the latter approach if you can.
I would suggest trying some sort of variant on Newton Raphson.
Construct a function Diff(k) that looks at the difference in area between your two graphs between fixed markers A and B.
mathematically I guess it would be integral ( x = A to B ){ f(x) - k * g(x) }dx
anyway realistically you could just subtract the values,
like if you range from X = -10 to 10, and you have a data point for f(i) and g(i) on each integer i in [-10, 10], (ie 21 datapoints )
then you just sum( i = -10 to 10 ){ f(i) - k * g(i) }
basically you would expect this function to look like a parabola -- there will be an optimum k, and deviating slightly from it in either direction will increase the overall area difference
and the bigger the difference, you would expect the bigger the gap
so, this should be a pretty smooth function ( if you have a lot of data points )
so you want to minimise Diff(k)
so you want to find whether derivative ie d/dk Diff(k) = 0
so just do Newton Raphson on this new function D'(k)
kick it off at k=1 and it should zone in on a solution pretty fast
that's probably going to give you an optimal computation time
if you want something simpler, just start with some k1 and k2 that are either side of 0
so say Diff(1.5) = -3 and Diff(2.9) = 7
so then you would pick a k say 3/10 of the way (10 = 7 - -3) between 1.5 and 2.9
and depending on whether that yields a positive or negative value, use it as the new k1 or k2, rinse and repeat
In case anyone stumbles upon this in the future, here is some code (c++)
The trick is to first sort the samples by the scaling factor that would result in the best fit for the 2 samples each. Then start at both ends iterate to the factor that results in the minimum absolute deviation (L1-norm).
Everything except for the sort has a linear run time => Runtime is O(n*log n)
/*
* Find x so that the sum over std::abs(pA[i]-pB[i]*x) from i=0 to (n-1) is minimal
* Then return x
*/
float linearFit(const float* pA, const float* pB, int n)
{
/*
* Algebraic solution is not possible for the general case
* => iterative algorithm
*/
if (n < 0)
throw "linearFit has invalid argument: expected n >= 0";
if (n == 0)
return 0;//If there is nothing to fit, any factor is a perfect fit (sum is always 0)
if (n == 1)
return pA[0] / pB[0];//return x so that pA[0] = pB[0]*x
//If you don't like this , use a std::vector :P
std::unique_ptr<float[]> targetValues_(new float[n]);
std::unique_ptr<int[]> indices_(new int[n]);
//Get proper pointers:
float* targetValues = targetValues_.get();//The value for x that would cause pA[i] = pB[i]*x
int* indices = indices_.get(); //Indices of useful (not nan and not infinity) target values
//The code above guarantees n > 1, so it is safe to get these pointers:
int m = 0;//Number of useful target values
for (int i = 0; i < n; i++)
{
float a = pA[i];
float b = pB[i];
float targetValue = a / b;
targetValues[i] = targetValue;
if (std::isfinite(targetValue))
{
indices[m++] = i;
}
}
if (m <= 0)
return 0;
if (m == 1)
return targetValues[indices[0]];//If there is only one target value, then it has to be the best one.
//sort the indices by target value
std::sort(indices, indices + m, [&](int ia, int ib){
return targetValues[ia] < targetValues[ib];
});
//Start from the extremes and meet at the optimal solution somewhere in the middle:
int l = 0;
int r = m - 1;
// m >= 2 is guaranteed => l > r
float penaltyFactorL = std::abs(pB[indices[l]]);
float penaltyFactorR = std::abs(pB[indices[r]]);
while (l < r)
{
if (l == r - 1 && penaltyFactorL == penaltyFactorR)
{
break;
}
if (penaltyFactorL < penaltyFactorR)
{
l++;
if (l < r)
{
penaltyFactorL += std::abs(pB[indices[l]]);
}
}
else
{
r--;
if (l < r)
{
penaltyFactorR += std::abs(pB[indices[r]]);
}
}
}
//return the best target value
if (l == r)
return targetValues[indices[l]];
else
return (targetValues[indices[l]] + targetValues[indices[r]])*0.5;
}

Resources