Generates a histogram representation of a data vector.
This method bins the input values into intervals and returns the histogram data,
including counts per bin, positions (typically bin centers), bin size, and min/max of the data range.
Suitable for visualizing data distributions.
V: A column vector (ColVec) containing the numerical data to be analyzed.
bin: The number of bins to divide the data range into. More bins provide finer granularity.
Returns:
A tuple containing:
- Counts: Number of elements in each bin
- Positions: Center positions of each bin
- BinSize: Width of each bin
- Vmin: Minimum value in the dataset
- Vmax: Maximum value in the dataset
Example:
Create a histogram of 1,000 samples drawn from a normal distribution.
Generates coordinate matrices from coordinate vectors.
This method creates two 2D arrays representing all pairs of x and y coordinates from the input vectors, which is often used for evaluating functions over a grid.
A tuple of two 2D arrays:
- The first array contains copies of the x vector arranged in rows.
- The second array contains copies of the y vector arranged in columns.
Example:
Generate a 2D grid from x = [1, 2, 3] and y = [10, 20]
Reads a two-dimensional elements in matrix from a file.
This method loads space-separated integers from each line of the specified file and constructs a matrix representation.
MatrixReadMatrix(stringfilename)
Param:
filename: The path to the input file containing the matrix data.
Returns:
A two-dimensional integer array containing the values read from the file.
Reads a row vector of numbers from a file.
This method parses a single line of space-separated values from the specified file and constructs a one-dimensional matrix representation.
RowVecReadRowVec(stringfilename)
Param:
filename: The path to the input file containing the row vector data.
Returns:
A one-dimensional matrix representing the row vector read from the file.
Reads a column vector of numbers from a file.
This method parses multiple lines of input from the specified file, with each line representing a single value in the column vector.
ColVecReadColVec(stringfilename)
Param:
filename: The path to the input file containing the column vector data.
Returns:
A one-dimensional matrix representing the column vector read from the file.
Example:
Read a column vector from a file named “colvec.txt”:
Writes a two-dimensional matrix of integers to a file.
This method serializes the matrix in space-separated format, with each row written on a new line in the target file.
voidWriteMatrix(MatrixA,stringfilename)
Param:
A: The matrix object to be written to the file.
filename: The path to the output file where the matrix will be saved.
Returns:
This method does not return a value (being a void method)
Example:
Write a matrix to a file named “matrixA.txt”:
// import librariesusingSystem;usingstaticSepalSolver.Math;stringpath="matrixA.txt";// Create a matrixMatrixA=newdouble[,]{{12,18,3},{15,25,30}};// Write to fileWriteMatrix(A,path);
Determines whether all values in a one-dimensional or two-dimensional array are true.
This method checks each element in the input array and returns true only if all values are true; otherwise, false.
boolAll(bool[]A)boolAll(bool[,]A)
Param:
A: The array of Boolean values to evaluate.
Returns:
True, if all elements in the array are true; otherwise, false.
Example:
Check if all values in a Boolean array or matrix are true:
Determines whether any value in a one-dimensional or two-dimensional array is true.
This method checks each element in the input array and returns true if at least one value is true; otherwise, false.
boolAny(bool[]A)boolAny(bool[,]A)
Param:
A: The array of Boolean values to evaluate.
Returns:
True, if at least one element in the array is true; otherwise, false.
Returns the indices of true values in a Boolean array or matrix, up to a maximum of k matches.
This method scans the input array and collects the positions of all values that evaluate to true, up to the specified limit.
Computes the quotient and remainder of integer division.
This method performs an integer division of a dividend, a by a divisor, b and returns both the quotient and remainder as a tuple.
(int,int)DivRem(inta,intb)
Param:
a: The dividend—value to be divided.
b: The divisor—value by which to divide.
Returns:
A tuple containing the integer quotient and remainder:(quotient, remainder).
Example:
Divide 17 by 5 and get both the quotient and remainder:
Converts a double-precision floating-point number to its string representation.
This method transforms the numeric input into a human-readable string format, suitable for display or formatting purposes.
Applies a scalar function to each element of a column vector or row vector or matrix.
This method maps a user-defined function across every element in the input array or matrix and produces a transformed array or matrix of the same size.
Reshapes a one-dimensional array of input into a matrix with specified dimensions.
This method returns a output with the given dimensions, populated with the data from the input array.
Calculates the length of the hypotenuse of a right-angled triangle given the lengths of the other two sides.This method computes z = Sqrt(Pow(x, 2) + Pow(y, 2)) by avoiding underflow and overflow.
Calculates the absolute value of an input.
This method returns the absolute value of the given input, which is the non-negative value of the input without regard to its sign.
Generates a one-dimensional 0r two-dimensional array of zeros with specified dimensions.
This method creates a vector of M rows or matrix of M rows and N columns, where every element is initialized to zero.
Generates a two-dimensional array of ones with specified dimensions.
This method creates a matrix of M rows and N columns, where every element is initialized to 1.0.
S: Array of integer rows and columns in the resulting matrix.
Returns:
An array of vector of size M or matrix of size M by N filled with ones.
Example:
Create a 2x3 matrix of ones:
// import librariesusingSystem;usingstaticSepalSolver.Math;//Generate Matrix 2 by 3 with all the element has 1.0double[,]ones=Ones(2,3);// Display matrixfor(inti=0;i<ones.Rows;i++){for(intj=0;j<ones.Cols;j++)Console.Write(ones[i,j]+" ");Console.WriteLine();}
Replicates a scalar value across a one-dimensional array or two-dimensional matrix of specified size.
This method returns a vector of size M or matrix of size M x N in which every element is initialized to the scalar value <c>A</c>.
S: Array of integer rows and columns in the resulting matrix.
Returns:
A matrix of dimensions M x N where all values are equal to A.
Example:
Create a 2x4 matrix filled with the value 3.14:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Replicate all elements of a matrix same.double[,]replicated=Repmat(3.14,2,4);// Display matrixfor(inti=0;i<replicated.Rows;i++){for(intj=0;j<replicated.Cols;j++)Console.Write(replicated[i,j]+" ");Console.WriteLine();}
Replicates each element of a matrix a specified number of times along both axes.
This method expands the input matrix by repeating each element M times row-wise (vertically) and N times column-wise (horizontally), returning the result as a new Matrix with repetitive elements.
MatrixRepelem(MatrixA,intM,intN)
Param:
A: The input matrix whose elements will be replicated.
M: The number of times to repeat each element along the row (vertical) direction.
N: The number of times to repeat each element along the column (horizontal) direction.
Returns:
A new Matrix instance containing the expanded result with replicated elements.
Example:
Create a 4x6 matrix by replicating a 2x2 matrix:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a 2 by 2 matrixMatrixA=newdouble[,]{{1,2},{3,4}}// Apply element-wise replicationMatrixexpanded=Repelem(A,2,3);// Display resultfor(inti=0;i<expanded.Rows;i++){for(intj=0;j<expanded.Cols;j++)Console.Write(expanded[i,j]+" ");Console.WriteLine();}
Computes the Kronecker product of two matrices.
This method generates a block matrix by multiplying each element of matrix X by the entire matrix Y, preserving the structure of X.
MatrixKron(MatrixX,MatrixY)
Param:
X: The first matrix (left operand) of the Kronecker product.
Y: The second matrix (right operand) of the Kronecker product.
Returns:
A Matrix representing the Kronecker product of X and Y.
Example:
Compute the Kronecker product of two 2x2 matrices:
// import librariesusingSystem;usingstaticSepalSolver.Math;// create a 2 by 2 matrixMatrixA=newdouble[,]{{1,2},{3,4}};;// create a 2 by 2 matrixMatrixB=newdouble[,]{{0,5},{6,7}};// Compute Kronecker productMatrixresult=Kron(A,B);// Display resultfor(inti=0;i<result.Rows;i++){for(intj=0;j<result.Cols;j++)Console.Write(result[i,j]+" ");Console.WriteLine();}
Generates a one-dimensional or two-dimensional matrix of random double-precision values between 0.0 (inclusive) and 1.0 (exclusive).
This method creates a matrix with M rows and N columns, where each element is independently sampled from a uniform distribution.
Generates an array (Vector) or matrix of normally distributed random double values.
This method creates a vector of size M or M * N matrix with each element independently sampled from a normal distribution characterized by the specified <c>mean</c> and <c>standard deviation</c>.
Generates a matrix of random double values from a triangular distribution.
This method creates an M x N matrix where each element is independently sampled from a triangular distribution defined by minimum bound value, mode of distribution likely, and maximum bound value.
Generates a linearly spaced array of double values between two endpoints.
This method produces a one-dimensional array of N evenly spaced values from a to b, inclusive. If N is 1, the array contains just a.
double[]Linspace(doublea,doubleb,intN=100)
Param:
a: The starting value of the range.
b: The ending value of the range.
N: The number of evenly spaced points to generate. Default is 100.
Returns:
An array containing N linearly spaced values between a and b.
Example:
Generate 10 points from -1 to 1:
// import librariesusingSystem;usingstaticSepalSolver.Math;//Generate point from -1 to 1double[]line=Linspace(-1.0,1.0,10);// Display resultforeach(doublexinline)Console.Write($"{x:F2} ");
Generates a logarithmically spaced array of double values between powers of 10.
This method creates a one-dimensional array with N values spaced evenly on a logarithmic scale, ranging from <c>10^a</c> to <c>10^b</c>, inclusive.
double[]Logspace(doublea,doubleb,intN=100)
Param:
a: The base-10 exponent of the starting value (10^a).
b: The base-10 exponent of the ending value (10^b).
N: The number of points to generate. Default is 100.
Returns:
An array of N values logarithmically spaced between 10^a and 10^b.
Example:
Generate 5 values from 10⁰ to 10²:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Generate logarithmically space between 1 and 100 inclusivedouble[]freqs=Logspace(0,2,5);// Display result, formated to 2 decimal placesforeach(doublexinfreqs)Console.Write($"{x:F2} ");
Performs one-dimensional linear interpolation.
This method estimates the output value at a query point <c>x</c> by linearly interpolating between known data points in <c>X</c> and corresponding values in <c>Y</c>.
doubleInterp1(ColVecX,ColVecY,doublex)
Param:
X: A column vector containing the known x-coordinates, which must be sorted in ascending order.
Y: A column vector containing the corresponding y-values.
x: The x-value at which to evaluate the interpolated result.
Returns:
A scalar value representing the linearly interpolated value at the given point x.
Example:
Estimate a y-value at x = 1.5 from lookup data using linear interpolation:
// import librariesusingSystem;usingstaticSepalSolver.Math;ColVecX=newColVec(newdouble[]{0.0,1.0,2.0,3.0});ColVecY=newColVec(newdouble[]{0.0,10.0,20.0,30.0});doublex=1.5;doubley=Interp1(X,Y,x);Console.WriteLine($"Interpolated value at x=1.5: {y}");
Extracts a specified column from a two-dimensional array.
This method retrieves the column at index j from the input matrix data and returns it as a one-dimensional array.
double[]Getcol(intj,double[,]data)
Param:
j: The zero-based index of the column to extract.
data: The two-dimensional array from which the column will be retrieved.
Returns:
An array representing the j_th column of the matrix data.
Example:
Extract the first column from a 3x3 matrix:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create 3 by 3 matrixdouble[,]matrix=newdouble[,]{{1.0,2.0,3.0},{4.0,5.0,6.0},{7.0,8.0,9.0}};// Get column 0 (first column)double[]col=Getcol(0,matrix);foreach(doublevalincol)Console.Write(val+" ");
Extracts a specified row from a two-dimensional array.
This method retrieves the row at index i from the input matrix data and returns it as a one-dimensional array.
double[]Getrow(inti,double[,]data)
Param:
i: The index of the row to extract.
data: The two-dimensional array from which the row will be retrieved.
Returns:
An array representing the i-th row of matrix data element.
Example:
Extract the third row from a 4x3 matrix:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a 4 by 3 matrixdouble[,]matrix={{1.0,2.0,3.0},{4.0,5.0,6.0},{7.0,8.0,9.0},{10.0,11.0,12.0}};// Get row 2 (third row)double[]row=Getrow(2,matrix);// Output the matrixforeach(doublevalinrow)Console.Write(val+" ");
Extracts specified columns from a two-dimensional array using an indexer.
This method returns a new Matrix containing only the columns of data specified by the I-indexer.
MatrixGetcols(indexerI,double[,]data)
Param:
I: An indexer object specifying the zero-based column indices to select.
data: The two-dimensional array from which columns are extracted.
Returns:
A Matrix composed of the selected columns from the input matrix data, in the order defined by I-indexer.
Example:
Extract columns 1 and 3 from a 3x4 matrix:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a 3 by 4 matrixMatrixmatrix=newdouble[,]{{10,20,30,40},{50,60,70,80},{90,100,110,120}};// Set the matrix index to be extractedindexerI=newindexer(newint[]{1,3});// select 2nd and 4th columns// Extract the matrixMatrixcols=Getcols(I,matrix);// Output the extracted matrixconsole.writeline($"The extracted matrix is: {cols}")
Extracts specified rows from a two-dimensional array using an indexer.
This method returns a new Matrix data composed of the rows from matrix data that correspond to the indices specified by I-indexer.
MatrixGetrows(indexerI,double[,]data)
Param:
I: An indexer object that specifies the zero-based indices of the rows to extract.
data: The two-dimensional array from which rows will be selected.
Returns:
A Matrix containing the rows of data specified by I-indexer, in the same order.
Example:
Extract the 1st and 3rd rows from a 4x3 matrix:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a 4 by 3 matrixMatrixmatrix=newdouble[,]{{10,20,30},{40,50,60},{70,80,90},{100,110,120}};// Set the matrix index to be extractedindexerI=newindexer(newint[]{0,2});// first and third rows// Extract the matrixMatrixrows=Getrows(I,matrix);// Output the extracted matrixconsole.writeline($"The extracted matrix is: {rows}")
Horizontally concatenates a scalar with a row vector. Also concatenates a matrix with a matrix. The two matrices must have equal row count.
This method concatenate a scalar value to a vector or matrix to a matrix and other combination returning a new vector or matrix with an additional leading element.
A, B: The input array (row or column vector) or matrix to which a will be prepended.
Returns:
A vector or matrix consisting of concatenated values.
Example:
Concatenate the value 1.0 to a row vector:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a row vectorRowVecB=newRowVec(newdouble[]{2.0,3.0,4.0});// Concatenate the scaler value and the vector together.RowVecresult=Hcart(1.0,B);// Output the resultconsole.writeline($"The concatenated matrix is: {rows}")
Output:
1 2 3 4
Example:
Horizontally concatenate two 2x2 matrices:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a 2 by 2 matrixMatrixA=newdouble[,]{{1,2},{3,4}};// Create a 2 by 2 matrixMatrixB=newdouble[,]{{5,6},{7,8}};ConcatenatethetwomatrixtogetherMatrixresult=Hcart(A,B);// Output the resultconsole.writeline($"The concatenated matrix is: {result}")
Vertically concatenates a scalar with a column vector or concatenates a matrix with a matrix. The two matrices must equal column count.
concatenate a scalar value to a vector or matrix to a matrix and other combination returning a new vector or matrix with an additional leading element.
a, b: The scalar value to be placed at the top or below of the resulting vector.
A, B: The input column vector or matrix whose elements will appear before or after a.
Returns:
A vector or matrix consisting of a followed by the entries of B.
Example:
Prepend a scalar to a column vector:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a vectorColVecB=newdouble[]{2.0,3.0,4.0};// Concatenate the scalar value and the vector togetherColVecresult=Vcart(1.0,B);// Output the resultconsole.writeline($"The concatenated matrix is: {result}")
Output:
1
2
3
4
Example:
Vertically concatenate two 2x2 matrices:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create 2 by 2 matrixMatrixA=newMatrix(newdouble[,]{{1,2},{3,4}});// Create 2 by 2 matrixMatrixB=newMatrix(newdouble[,]{{5,6},{7,8}});//Concatenate the two matricesMatrixresult=Vcart(A,B);// Output the resultconsole.writeline($"The concatenated matrix is: {result}")
Raises a real or complex numbers or elements in a vector or matrix to the power of another.
This method computes the result of raising x to the power n, returning x^n.
Computes the first-order discrete difference of a one-dimensional or two-dimensional array.
This method returns a new array where each element is the difference between consecutive elements of the input array X.
Performs element-wise (Hadamard) multiplication of two column vectors or multiplication of two matrices. Vector and Matrix A and B must have the same size.
This method multiplies corresponding elements of A and B, producing a new vector or matrix of the same length.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create two column vector A and BColVecA=newdouble[]{1.0,2.0,3.0};ColVecB=newdouble[]{4.0,5.0,6.0};// Calculation of element-wise multiplicationColVecresult=MultTW(A,B);// Output the resultconsole.writeline($"Multiplication of two column-wise vector: {result}")
Output:
Multiplication of two column-wise vector:
4
10
18
Example:
Multiply two 2x2 matrices element-wise:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create Matrix A and Matrix BMatrixA=newdouble[,]{{1,2},{3,4}};MatrixB=newdouble[,]{{5,6},{7,8}};// Calculation of element-wise multiplicationMatrixresult=MultTW(A,B);// Output the resultconsole.writeline($"Multiplication of two Matrix-wise: {result}")
Performs element-wise division of two column vectors or matrices.No element in the divisor vector or matrix should be zero.
This method divides each element of column vector or matrix A by the corresponding element in column vector or matrix B, returning a new vector or matrix of the same size.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create column vector A and vector BColVecA=newdouble[]{10.0,20.0,30.0};ColVecB=newdouble[]{2.0,4.0,5.0};// Calculation of element-wise divisionColVecresult=DivTW(A,B);// Output the resultconsole.writeline($"Division of two column-wise: {result}")
Output:
5
5
6
Example:
Divide two 2x2 matrices element-wise:
// import librariesusingSystem;usingstaticSepalSolver.Math;//Create matrix A and matrix BMatrixA=newdouble[,]{{10,20},{30,40}};MatrixB=newdouble[,]{{2,4},{5,10}};// Calculation of element-wise divisionMatrixresult=DivTW(A,B);// Output the resultconsole.writeline($"Division of two matrix-wise: {result}")
Performs element-wise exponentiation of two column vectors or matrices.
This method raises each element of vector or matrix A to the corresponding power in vector or matrix B, producing a new vector or matrix. The size of vector or matrix A and B must be the same.
B: The exponent vector or matrix. Must have the same length as A.
Returns:
A vector or matrix containing the element-wise exponentiation
Example:
Raise elements of one vector to the powers in another:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create vector A and vector BColVecA=newdouble[]{2.0,3.0,4.0};ColVecB=newdouble[]{3.0,2.0,0.5};// Calculation of element-wise exponentColVecresult=PowTW(A,B);// Output the resultconsole.writeline($"Exponent of two column-wise: {result}")
Output:
8
9
2
Example:
Raise each element of one 2x2 matrix to the powers in another:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create matrix A and BMatrixA=newdouble[,]{{2.0,3.0},{4.0,36.0}};MatrixB=newdouble[,]{{3.0,2.0},{1.0,0.5}};// Calculation of element-wise exponentMatrixresult=PowTW(A,B);// Output the resultconsole.writeline($"Exponent of two matrix-wise: {result}")
Rounds a floating-point number or complex number or each element in a vector or matrix to a specified number of decimal places.
This method returns a double value rounded to the nearest number with the specified number of decimal places using standard rounding rules (round half to even).
x: The double-precision floating-point number or complex number or each element in a vector or matrix to be rounded.
decP: The number of decimal places to round to. Default is 0 (rounds to nearest integer). Must be between 0 and 15.
Returns:
A double value rounded to the specified number of decimal places.
Example:
Round a number, 3.14159 to the nearest integer:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a double valuedoublevalue=3.14159;// Round to nearest integer (default behavior)doubleresult=Round(value,0);// Output the resultconsole.writeline($"The rounded value is: {result}")
Calculates the square root of a specified number.
This method returns the positive square root of the input value. For negative inputs, the result is NaN (Not a Number).
x: The number whose square root is to be calculated. Must be non-negative for real results.
Returns:
The positive square root of x. Returns NaN if x is negative, and positive infinity if x is positive infinity.
Example:
Calculate the square root of a positive number, 25:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a double valuedoublevalue=25.0;// Calculate the square rootdoubleresult=Sqrt(value);// Output the resultconsole.writeline($"The square root is: {result}")
The square of x (x * x). Returns positive infinity if the result overflows.
Example:
Calculate the square of a positive number:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a double valuedoublevalue=5.0;// Calculate the squaredoubleresult=Sqr(value);// Output the resultconsole.writeline($"The square is: {result}")
Returns the largest integer less than or equal to the specified number.
This method rounds down to the nearest integer, always moving toward negative infinity regardless of the sign of the input.
doubleFloor(doublex)
Param:
x: The double-precision floating-point number to floor.
Returns:
The largest integer less than or equal to x. If x is already an integer, returns x unchanged.
Example:
Floor a positive decimal number:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a positive decimal valuedoublevalue=4.7;// Calculate the floordoubleresult=Floor(value);// Output the resultconsole.writeline($"The floor is: {result}")
Returns the smallest integer greater than or equal to the specified number.
This method rounds up to the nearest integer, always moving toward positive infinity regardless of the sign of the input.
doubleCeil(doublex)
Param:
x: The double-precision floating-point number to ceiling.
Returns:
The smallest integer greater than or equal to x. If x is already an integer, returns x unchanged.
Example:
Ceiling a positive decimal number:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create a positive decimal valuedoublevalue=4.2;// Calculate the ceilingdoubleresult=Ceil(value);// Output the resultconsole.writeline($"The ceiling is: {result}")
Returns the larger of two or more real or, floating-point number or maximum among elelments of a vector or matrices.
This method compares two integer values and returns the one with the greater value.
The maximum number from two or more given vectors or matrices. If A and B are equal, returns either value.
Example:
Find the maximum of two positive integers:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create two integer valuesintvalueA=15;intvalueB=23;// Find the maximumintresult=Max(valueA,valueB);// Output the resultconsole.writeline($"The maximum is: {result}")
Output:
23
Example:
Find the element-wise maximum of two 2x2 matrices:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create first 2x2 matrixMatrixA=newMatrix(newdouble[,]{{1,8},{5,2}});// Create second 2x2 matrixMatrixB=newMatrix(newdouble[,]{{3,4},{1,7}});// Find element-wise maximumMatrixresult=Max(A,B);// Output the resultconsole.writeline($"The maximum is: {result}")
The smaller of the two input values. If A and B are equal, returns either value.
Example:
Find the minimum of two positive integers:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Create two integer valuesintvalueA=15;intvalueB=23;// Find the minimumintresult=Min(valueA,valueB);// Output the resultconsole.writeline($"The minimum is: {result}")
Calculates the sine of the specified angle in radians.
This method returns the sine of the input angle, where the angle is measured in radians. The result is between -1 and 1.
x: The angle in radians for which to calculate the sine.
Returns:
The sine of x, ranging from -1 to 1. Returns 0 if x is positive or negative infinity.
Example:
Calculate the sine of common angles:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Calculate sine of π/2 radians (90 degrees)doubleangle=Pi/2;doubleresult=Sin(angle);// Output the resultconsole.writeline($"Sin(π/2) = {result}")
Calculates the arcsine (inverse sine) of the specified value.
This method returns the angle in radians whose sine is the specified value. The input must be between -1 and 1, and the result is between -π/2 and π/2.
x: The sine value for which to calculate the arcsine. Must be between -1 and 1 inclusive.
Returns:
The angle in radians whose sine equals x, ranging from -π/2 to π/2. Returns NaN if x is outside the range [-1, 1].
Example:
Calculate the arcsine of common values:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Calculate arcsine of 1 (which should be π/2)doublevalue=1.0;doubleresult=Asin(value);// Output the resultconsole.writeline($"Asin(1) = {result}")
Output:
Asin(1) = 1.5707963267948966
Example:
Calculate the arcsine of zero and negative values:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Calculate arcsine of 0 and -1doubleasinZero=Asin(0);doubleasinNegativeOne=Asin(-1);// Output the resultsconsole.writeline($"Asin(0) = {asinZero}")console.writeline($"Asin(-1) = {asinNegativeOne}")
Calculates the cosine of the specified angle in radians.
This method returns the cosine of the input angle, where the angle is measured in radians. The result is between -1 and 1.
Calculates the arccosine (inverse cosine) of the specified value.
This method returns the angle in radians whose cosine is the specified value. The input must be between -1 and 1, and the result is between 0 and π.
x: A scalar number or one-dimensional or two-dimensional array for which to calculate the arccosine. Must be between -1 and 1 inclusive.
Returns:
The angle in radians whose cosine equals x, ranging from 0 to π. Returns NaN if x is outside the range [-1, 1].
Example:
Calculate the arccosine of common values:
// import librariesusingSystem;usingstaticSepalSolver.Math;// Calculate arccosine of 1 (which should be 0)doublevalue=1.0;doubleresult=Acos(value);// Output the resultconsole.writeline($"Acos(1) = {result}")
Calculates the tangent of the specified angle in radians.
This method returns the tangent of the input angle, where the angle is measured in radians. The tangent function has vertical asymptotes at odd multiples of π/2.
Computes the arctangent (inverse tangent) of a specified number.
This method returns the angle in radians whose tangent is the specified number. The angle is in the range -π/2 to π/2 radians.
Computes the hyperbolic sine of a specified number.
This method returns the hyperbolic sine of x, defined as (e^x - e^(-x))/2. The hyperbolic sine function is an odd function with domain (-∞, +∞) and range (-∞, +∞).
x: A scalar number one-dimensional or two-dimensional array representing the value for which the hyperbolic sine is to be computed.
Returns:
A double representing the hyperbolic sine of x.
Returns PositiveInfinity if x is PositiveInfinity.
Returns NegativeInfinity if x is NegativeInfinity.
Returns NaN if x is NaN.
Example:
Calculate the hyperbolic sine of a positive value:
// Import librariesusingSystem;usingstaticSepalSolver.Math;// Define the input valuedoublex=2.0;// Calculate the hyperbolic sinedoubleresult=Sinh(x);// Output the resultConsole.WriteLine($"Sinh({x}) = {result}");Console.WriteLine($"Verification: (e^{x} - e^(-{x}))/2 = {(Math.Exp(x) - Math.Exp(-x)) / 2}");
Computes the hyperbolic cosine of a specified number.
This method returns the hyperbolic cosine of x, defined as (e^x + e^(-x))/2. The hyperbolic cosine function is an even function with domain (-∞, +∞) and range [1, +∞).
x: A scalar number or one-dimensional or two-dimensional array representing the value for which the hyperbolic cosine is to be computed.
Returns:
A double representing the hyperbolic cosine of x, always greater than or equal to 1.
Returns PositiveInfinity if x is PositiveInfinity or NegativeInfinity.
Example:
Calculate the hyperbolic cosine of a positive value:
// Import librariesusingSystem;usingstaticSepalSolver.Math;// Define the input valuedoublex=1.5;// Calculate the hyperbolic cosinedoubleresult=Cosh(x);// Output the resultConsole.WriteLine($"Cosh({x}) = {result}");Console.WriteLine($"Verification: (e^{x} + e^(-{x}))/2 = {(Math.Exp(x) + Math.Exp(-x)) / 2}");
Computes the hyperbolic tangent of a given value.
The hyperbolic tangent is defined as (e^x - e^(-x)) / (e^x + e^(-x)) and maps any real number to the range (-1, 1).
x: A double-precision floating-point number representing the value for which to calculate the hyperbolic tangent.
Returns:
The hyperbolic tangent of a number.
Example:
Evaluate hyperbolic tangent of the number, 1
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the hyperbolic tangent of a numberdoubleresult=Tanh(1.0);// Output the resultConsole.WriteLine($"Tanh(1.0) = {result}");
Calculates the inverse hyperbolic tangent (area hyperbolic tangent) of a specified value.
The inverse hyperbolic tangent is defined as 0.5 * ln((1 + x) / (1 - x)).
The function is undefined for values less than or equal to -1 and greater than or equal to 1.
x: A one-dimensional or two-dimensional array or double-precision floating-point number in the range (-1, 1), representing the value for which to compute the inverse hyperbolic tangent.
Returns:
The inverse hyperbolic tangent of the number, x.
Example:
Evaluate the inverse hyperbolic tangent of the number, 0.5.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the inverse hyperbolic tangent of a numberdoubleresult=Atanh(0.5);// Output the resultConsole.WriteLine($"Atanh(0.5) = {result}");
x: A one-dimensional or two-dimensional array or double-precision floating-point number representing the power to raise Euler’s number (e) to.
Returns:
The exponential of a number, i.e., e raised to the power x.
Example:
Evaluate the exponential value of number, 2.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the exponential of a numberdoubleresult=Exp(2.0);// Output the resultConsole.WriteLine($"Exp(2.0) = {result}");
x: A one-dimensional or two-dimensional array or double-precision floating-point number greater than zero, representing the value whose logarithm is to be calculated.
Returns:
The natural logarithm (ln) of a number.
Example:
Evaluate the natural logaraithm of the number, 10
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the natural logarithm of a numberdoubleresult=Log(10.0);// Output the resultConsole.WriteLine($"Log(10.0) = {result}");
x: A one-dimensional or two-dimensional array or double-precision floating-point number greater than zero, representing the value whose base-2 logarithm is to be calculated.
Returns:
The base-2 logarithm of the number, x.
Example:
Evaluate log 16 to base 2.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the base-2 logarithm of a numberdoubleresult=Log2(16.0);// Output the resultConsole.WriteLine($"Log2(16.0) = {result}");
x: A one-dimensional or two-dimensional array or double-precision floating-point number greater than zero, representing the value whose base-10 logarithm is to be calculated.
Returns:
The base-10 logarithm (common logarithm) of the number, x.
Example:
Evaluate the logarithm of 1000 to base 10.
// import librariesusingSystem;usingstaticSepalSolver.Math;// Compute the base-10 logarithm of a numberdoubleresult=Log10(1000.0);// Output the resultConsole.WriteLine($"Log10(1000.0) = {result}");
Computes the modified Bessel function of the first kind Iₙ(x).
This method evaluates the exponentially scaled modified Bessel function of the first kind for a given order and value.
Computes the Bessel function of the second kind Yₙ(x).
This method evaluates the Weber or Neumann Bessel function of the first kind for a given order and value.
Computes the Bessel function of the second kind Kₙ(x).
This method evaluates the exponentially scaled modified Bessel function for a given order and value.
Computes the Gamma function Γ(z), which generalizes the factorial function to real and complex numbers.
This method evaluates the Gamma function Γ(x), for a given real positive numbers or complex numbers.
Creates and returns a configuration object for solver settings.
This method allows customization of solver behavior such as step size, tolerance levels, iteration limits, and parallel execution. It also supports a user-defined Jacobian function to improve solver efficiency and accuracy.
Display: Optional. If <c>true</c>, enables display of solver progress and results during execution. Defaults to <c>false</c>.
StepFactor: Optional. A scaling factor for the initial step size used in iterative solvers.
RelTol: Optional. Relative tolerance. The solver stops when the relative change in the solution is below this threshold.
AbsTol: Optional. Absolute tolerance. The solver stops when the absolute change in the solution is below this threshold.
MaxIter: Optional. Maximum number of iterations allowed for the solver.
MaxFunEvals: Optional. Maximum number of function evaluations allowed.
UseParallel: Optional. If <c>true</c>, enables parallel computation for supported solvers.
UserDefinedJac: Optional. A user-defined function that returns the Jacobian matrix of the system. This can improve convergence speed and accuracy.
Returns:
Information about the problem solved like, number of iteration, number of function call and other estimated parameters.
Example:
Consider the root of the function below and evaluation information displayed using SolverSet. You can set your desired number of iteration and other parameters. It displaced information like number of iteration, number of function call and other estimated parameters. This information provides an insight about the
activities that takes inside the method during and after evaluation of the set function.
Compute the root of \(x^3 - 10 = 0\)
usingSepalSolver;usingstaticSepalSolver.Math;// Define an objective functionstaticdoublefun(doublex)=>Pow(x,3)-10;// Call the SolverSet method and set initial guessvaropts=SolverSet(Display:true);doublex0=1.5;// Solve the optimization problem and display of runtime information by SolverSetConsole.WriteLine($"Information during Fzero Calculation displayed by SolverSet");doubleroot=Fzero(fun,x0,opts);Console.WriteLine($"Root of the function, F(x) is : {root.T}");
Output:
Information during Fzero Calculation displayed by SolverSet
Search for an interval around 1.5 containing a sign change:
fun-count a f(a) b f(b) Procedure
1 1.5e+0 -6.625e+0 1.5e+0 -6.625e+0 initial interval
3 1.4576e+0 -6.9034e+0 1.5424e+0 -6.3304e+0 search
5 1.44e+0 -7.014e+0 1.56e+0 -6.2036e+0 search
7 1.4151e+0 -7.166e+0 1.5849e+0 -6.0192e+0 search
9 1.38e+0 -7.3719e+0 1.62e+0 -5.7485e+0 search
11 1.3303e+0 -7.6458e+0 1.6697e+0 -5.345e+0 search
13 1.26e+0 -7.9996e+0 1.74e+0 -4.732e+0 search
15 1.1606e+0 -8.4367e+0 1.8394e+0 -3.7765e+0 search
17 1.02e+0 -8.9388e+0 1.98e+0 -2.2376e+0 search
19 8.2118e-1 -9.4463e+0 2.1788e+0 3.4345e-1 search
Solving for solution between 0.821177 and 2.178823
fun-count x f(x) Procedure
19 2.1788e+0 3.4345e-1 initial
20 2.1312e+0 -3.2017e-1 interpolation
21 2.1542e+0 -3.6617e-3 interpolation
22 2.1544e+0 7.4508e-7 interpolation
23 2.1544e+0 -9.0964e-11 interpolation
24 2.1544e+0 1.7764e-15 interpolation
Root of the function, F(x) is: 2.154434690031884
Configures and returns a set of optimization parameters.
This method allows users to customize various solver settings such as tolerances, iteration limits, and display options. These settings influence the behavior and performance of optimization algorithms.
Display: Optional. If set to <c>true</c>, displays solver progress and results during and after execution. Defaults to <c>false</c>.
FuncTol: Optional. Function tolerance. The solver stops when the change in the objective function value is less than this threshold.
OptimalityTol: Optional. Optimality tolerance. Determines the acceptable level of optimality for the solution.
StepTol: Optional. Step tolerance. The solver stops if the step size becomes smaller than this value.
ConstraintTol: Optional. Constraint tolerance. Specifies the acceptable violation level for constraints.
Weight: Optional. A vector of weights used in weighted optimization problems.
MaxIter: Optional. Maximum number of iterations allowed for the solver.
MaxFunEvals: Optional. Maximum number of function evaluations allowed.
UseParallel: Optional. If set to <c>true</c>, enables parallel computation for supported solvers.
Pltfun: Optional. A plotting function or delegate that visualizes the optimization process.
PopulationSize: Optional. Specifies the population size for population-based algorithms (e.g., genetic algorithms).
LMUpdate: Optional. Specifies the update strategy for the Levenberg-Marquardt algorithm.
Returns:
Information about the problem solved like, number of iteration, number of function call and other estimated parameters.
Example:
Consider the optimization of a Rosenbrock function below and evaluation information displayed using OptimSet. You can set your desired number of iteration and other parameters. It displaced information like number of iteration, number of function call and other estimated parameters. This information provides an insight about the
activities that takes inside the method during and after the estimation of the Rosenbrock problem.
usingSepalSolver;usingstaticSepalSolver.Math;// Define the Rosenbrock functionFunc<ColVec,double>objective=x=>Pow(1-x[0],2)+100*Pow(x[1]-Pow(x[0],2),2);// Call the OptimSet method and set initial guessvaropts=OptimSet(Display:true,MaxIter:200,StepTol:1e-6,OptimalityTol:1e-6);double[]x0=newdouble[]{-1.2,1};// Solve the optimization problem and display of runtime information by OptimSetvarsolution=Fminsearch(objective,x0,null,null,null,null,opts);Console.WriteLine($"Optimized Solution: {solution.T}");
Computes the root of a nonlinear equation.
This method finds the root (zero) of the specified nonlinear function, starting from an initial guess. An optional parameter allows customization of solver settings.
fun: The nonlinear function whose root is to be computed. The function must take a double and return a double.
x0: The initial guess for the root or the interval bounding the root.
options: Optional. Solver settings that specify parameters like tolerance, maximum iterations, or other configurations. Defaults to null if not provided.
Returns:
The computed root of the nonlinear equation.
Example:
Compute the root of \(x^3 - 10 = 0\)
// Import librariesusingSystem;usingSepalSolver;usingstaticSepalSolver.Math;// Define the functionFunc<double,double>function=x=>Pow(x,3)-10;// Compute the root with default optionsvarroot=Fzero(function,2.0);Console.WriteLine($"Root: {root}");
Finds the roots of nonlinear equations.
This method computes the root (zero) of the specified system of nonlinear functions, starting from an initial guess. Optional solver settings can be provided to customize the process.
fun: The nonlinear function whose root is to be computed. The function can take a double or complex scalar or array values as input and return a scaler or complex or array values.
x0: The initial guess for the root of the function.
options: Optional. Solver settings that specify parameters such as tolerance, maximum iterations, or other configurations. Defaults to null if not provided.
Returns:
The computed root or root(s) of the nonlinear equations.
// import librariesusingSystem;usingSepalSolver;usingstaticSepalSolver.Math;double[]x0,res;ColVecx// define the functionColVecfun(ColVecx){doublex1=x[0],x2=x[1],x3=x[2];res=[3*x1-Cos(x2*x3)-0.5,x1*x1-81*Pow(x2+0.1,2)+Sin(x3)+1.06,Exp(-x1*x2)+20*x3+(10*pi-3)/3];returnres;};// set initial guessx0=[0.1,0.1,-0.1];// call the solverx=Fsolve(fun,x0);// display the resultConsole.WriteLine(x);// display the resultConsole.WriteLine(x);
Solves a linear programming problem using the Linprog method.
This method optimizes a linear objective function under constraints defined by
inequality and equality systems, as well as variable bounds.
c: The row vector representing the coefficients of the linear objective function to be minimized.
AInEq: Optional. The matrix representing inequality constraint coefficients.
If null, no inequality constraints are applied.
bInEq: Optional. The column vector representing the right-hand side values of the inequality constraints.
If null, no inequality constraints are applied.
AEq: Optional. The matrix representing equality constraint coefficients.
If null, no equality constraints are applied.
bEq: Optional. The column vector representing the right-hand side values of the equality constraints.
If null, no equality constraints are applied.
Lb: Optional. The column vector representing the lower bounds for the variables.
If null, the variables are unbounded below.
Ub: Optional. The column vector representing the upper bounds for the variables.
If null, the variables are unbounded above.
options: Optional. Solver settings that allow customization of parameters such as
tolerance, maximum iterations, or other configurations. Defaults to null if not provided.
Returns:
A column vector representing the optimized solution to the linear programming problem.
Example:
Solve a linear programming problem with the objective function
Solves an Integer Linear Programming (ILP) problem using the Intlinprog method.
This method optimizes a linear objective function under constraints defined by
inequality and equality systems, variable bounds, and ensures that specific variables
are integers.
c: The row vector representing the coefficients of the linear objective function to be minimized.
IntVar: The array of indices specifying which variables must be integers.
AInEq: Optional. The matrix representing inequality constraint coefficients.
If null, no inequality constraints are applied.
bInEq: Optional. The column vector representing the right-hand side values of the inequality constraints.
If null, no inequality constraints are applied.
AEq: Optional. The matrix representing equality constraint coefficients.
If null, no equality constraints are applied.
bEq: Optional. The column vector representing the right-hand side values of the equality constraints.
If null, no equality constraints are applied.
Lb: Optional. The column vector representing the lower bounds for the variables.
If null, the variables are unbounded below.
Ub: Optional. The column vector representing the upper bounds for the variables.
If null, the variables are unbounded above.
options: Optional. Solver settings that allow customization of parameters such as
tolerance, maximum iterations, or other configurations. Defaults to null if not provided.
Returns:
A column vector representing the optimized integer solution to the Integer Linear Programming problem.
Example:
Solve an Integer Linear Programming problem with the objective function:
// Import librariesusingSystem;usingSepalSolver;usingstaticSepalSolver.Math;// Define the coefficientsRowVecc=newdouble[]{-60,-40,-70};MatrixAInEq=newdouble[,]{{4,2,3},{3,2,2},{2,1,4}};ColVecbInEq=newdouble[]{60,40,36};int[]IntVar=[0,1,2];// x1, x2, x3 are an integers// Solve the problemColVecsolution=Intlinprog(c,IntVar,AInEq,bInEq,null,null,Zeros(3));Console.WriteLine($"Integer Solution: {solution}");
Finds the local minimum of a nonlinear scalar objective function.
This method uses an iterative solver to minimize the given function, optionally subject to constraints and bounds.
Finds the minimum of a scalar objective function subject to various constraints,
including inequality, equality, and bound constraints using sequential quadratic programming.
Finds the minimum of a multivariable objective function using the BFGS quasi-Newton method.
The method utilizes gradient-based optimization to iteratively improve the solution to unconstrained problems. It is optionally subject to constraints and bounds.
Performs nonlinear least squares curve fitting using the Levenberg-Marquardt algorithm.
The function optimizes model parameters to best fit measured data by minimizing the residuals.
Model: The nonlinear model function to be fitted. Takes an independent variable and parameter vector
as inputs and returns computed values.
x0: Initial guess for model parameters.
IndVar: The independent variable values.
Measured: The observed dependent variable values.
funInEq: Optional. Function defining inequality constraints on parameters.
funEq: Optional. Function defining equality constraints on parameters.
lb: Optional. Lower bound constraints for parameters.
ub: Optional. Upper bound constraints for parameters.
options: Optional solver settings such as tolerance and maximum iterations.
Returns:
Returns a tuple containing the optimized parameter values, exit flag, residual norm, parameter uncertainties,
estimated model output, output uncertainties, and iteration history.
Example:
Fitting a given data points to time dependant model given below:
\[y(x, t) = x_3\exp(x_1t) + x_4\exp(-x_2t)\]
usingSystem;usingSepalSolver;ColVecxdata,ydata,times,y_est,filltime,sgy,filly,lower,upper;ColVecnoise=Rand(100);double[]x0;xdata=Linspace(0,1);// Create the modelstaticColVecfun(ColVecx,ColVecxdata)=>x[2]*Exp(x[0]*xdata)+x[3]*Exp(x[1]*xdata);// Define observed measurement dataydata=fun(x0=[-4,-5,4,-4],xdata)+0.02*noise;// Initial parameter guessx0=[-1,-2,1,-1];varopts=OptimSet(Display:true,MaxIter:200,StepTol:1e-6,OptimalityTol:1e-6);// Fit the modelvarans=Lsqcurvefit(fun,x0,xdata,ydata,options:opts);AnimateHistory(fun,xdata,ydata,ans.history);
Performs optimization using the Genetic Algorithm (GA), a technique inspired by natural selection.
GA evolves a population of solutions iteratively to find near-optimal solutions for nonlinear problems.
fun: The function that represents the implicit ODE. The function should accept three doubles (time, state, and its derivative) and return a double representing the derivative of the state.
t0: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
y0: The initial value of the dependent variable (state).
ytruth: An array of intergers indicating which component of y0 is fixed and which is not.
yp0: The initial time derivative of the dependent variable (state).
yptruth: An array of intergers indicating which component yp0 is fixed and which is not.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
double y0: modified initial state.
double yp0: modified initial rate of change.
Remark:
decic changes as few components of the guess as possible. You can specify that certain components are to be held fixed by setting ytruth(i) = 1 if no change is permitted
in the guess for Y0(i) and 0 otherwise.An empty array for yptruth is interpreted as allowing changes in all entries.yptruth is handled similarly.
You cannot fix more than length(Y0) components.Depending on the problem, it may not be possible to fix this many.It also may not be possible to fix certain components of Y0 or YP0.
It is recommended that you fix no more components than necessary.
Example:
Determine the consistent initial condition for the implicit ODE \(~ty^2y'^3 - y^3y'^2 + t(t^2 + 1)y' - t^2y = 0~\) with initial condition \(~y(0) = \sqrt{1.5}~\).
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticdoublefun(doublet,doubley,doubleyp)=>t*y*y*yp*yp*yp-y*y*y*yp*yp+t*(t*t+1)*yp-t*t*y;varopts=Odeset(Stats:true);doublet0=1,y0=Sqrt(t0*t0+1/2.0),yp0=0;(y0,yp0)=decic(fun,t0,y0,1,yp0,0);// print result to consoleConsole.WriteLine($"y0 = {y0}");Console.WriteLine($"yp0 = {yp0}");
Output:
y0 = 1.2247
yp0 = 0.8165
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves non stiff ordinary differential equations (ODE) using the Bogacki-Shampine method (Ode23).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses the Bogacki-Shampine method (Ode23) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = (1 - y^2)y' - y~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 2]\).
First we have to convert this to a system of first order differential equations,
\[\begin{split}\begin{array}{rcl}
y' &=& v \\
v' &=& (1 - y^2)v - y
\end{array}\end{split}\]
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp1(doublet,ColVecy){double[]dy;returndy=[y[1],(1-y[0]*y[0])*y[1]-y[0]];}//Solve ODE(ColVecT,MatrixY)=Ode23(vdp1,[2,0],[0,20]);// Plot the resultPlot(T,Y,"-o");Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1) with ODE23");SaveAs("Van-der-Pol-(μ=1)-Ode23.png");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves non stiff ordinary differential equations (ODE) using the Dormand-Prince method (Ode45).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses the Dormand-Prince method (Ode45) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = (1 - y^2)y' - y~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 2]\).
First we have to convert this to a system of first order differential equations,
\[\begin{split}\begin{array}{rcl}
y' &=& v \\
v' &=& (1 - y^2)v - y
\end{array}\end{split}\]
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp1(doublet,ColVecy){double[]dy;returndy=[y[1],(1-y[0]*y[0])*y[1]-y[0]];}//Solve ODE(ColVecT,MatrixY)=Ode45(vdp1,[2,0],[0,20]);// Plot the resultPlot(T,Y,"-o");Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1) with ODE45");SaveAs("Van-der-Pol-(μ=1)-Ode45.png");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves non stiff ordinary differential equations (ODE) using the Jim Verner 5th and 6th order pair method (Ode56).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses the Jim Verner 5th and 6th order pair method (Ode56) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = (1 - y^2)y' - y~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 20]\).
First we have to convert this to a system of first order differential equations,
\[\begin{split}\begin{array}{rcl}
y' &=& v \\
v' &=& (1 - y^2)v - y
\end{array}\end{split}\]
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp1(doublet,ColVecy){double[]dy;returndy=[y[1],(1-y[0]*y[0])*y[1]-y[0]];}//Solve ODE(ColVecT,MatrixY)=Ode56(vdp1,[2,0],[0,20]);// Plot the resultPlot(T,Y,"-o");Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1) with ODE56");SaveAs("Van-der-Pol-(μ=1)-Ode56.png");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves non stiff ordinary differential equations (ODE) using the Jim Verner 7th and 8th order pair method (Ode78).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses the Jim Verner 7th and 8th order pair method (Ode78) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = (1 - y^2)y' - y~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 20]\).
First we have to convert this to a system of first order differential equations,
\[\begin{split}\begin{array}{rcl}
y' &=& v \\
v' &=& (1 - y^2)v - y
\end{array}\end{split}\]
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp1(doublet,ColVecy){double[]dy;returndy=[y[1],(1-y[0]*y[0])*y[1]-y[0]];}//Solve ODE(ColVecT,MatrixY)=Ode78(vdp1,[2,0],[0,20]);// Plot the resultPlot(T,Y,"-o");Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1) with ODE78");SaveAs("Van-der-Pol-(μ=1)-Ode78.png");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves non stiff ordinary differential equations (ODE) using the Jim Verner 8th and 9th order pair method (Ode89).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses the Jim Verner 8th and 9th order pair method (Ode89) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = (1 - y^2)y' - y~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 20]\).
First we have to convert this to a system of first order differential equations,
\[\begin{split}\begin{array}{rcl}
y' &=& v \\
v' &=& (1 - y^2)v - y
\end{array}\end{split}\]
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp1(doublet,ColVecy){double[]dy;returndy=[y[1],(1-y[0]*y[0])*y[1]-y[0]];}//Solve ODE(ColVecT,MatrixY)=Ode89(vdp1,[2,0],[0,20]);// Plot the resultPlot(T,Y,"-o");Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1) with ODE89");SaveAs("Van-der-Pol-(μ=1)-Ode89.png");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves stiff ordinary differential equations (ODE) using Adaptive Diagonally Implicit RungeKutta of 4th and 5th Order Method (Ode45s).
Param:
dydx: The function that represents the ODE. The function should accept two doubles (time and state) and return a double representing the derivative of the state.
initcon: The initial value of the dependent variable (state).
tspan: An array of time points at which the solution is desired. The first element is the initial time, and the last element is the final time.
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses Adaptive Diagonally Implicit RungeKutta of 4th and 5th Order Method (Ode45s) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~d^2y/dt^2 = 10^{5}((1 - y^2)y' - y)~\) with initial condition \(~y(0) = [2, 0]~\) over the interval \([0, 6.3]\).
First we have to convert this to a system of first order differential equations,
// import librariesusingSystem;usingSepalSolver.Math;//define ODEstaticColVecvdp2(doublet,ColVecy){double[]dy;returndy=[y[1],1e5*((1-y[0]*y[0])*y[1]-y[0])];}//Solve ODE(ColVecT,MatrixY)=Ode45s(vdp2,[2,0],[0,6.3]);// Plot the resultPlot(T,Y);Xlabel("Time t");Ylabel("Soluton y");Legend(["y_1","y_2"],Alignment.UpperLeft);Title("Solution of van der Pol Equation (μ = 1e5) with ODE45s");SaveAs("Van-der-Pol-(μ=1e5)-Ode45s");
Output:
cref=System.ArgumentNullException is Thrown when the dydx is null.
cref=System.ArgumentException is Thrown when the tspan array has less than two elements.
Solves inmplicit ordinary differential equations (ODE) using Adaptive Diagonally Implicit RungeKutta of 4th and 5th Order Method (Ode45i).
Param:
fun: The function that represents the implicit ODE. The function should accept three doubles (time, state, and its derivative) and return a double representing the derivative of the state.
initcon: A tuple containing two elements:
* double y0: initial state.
* double yp0: initial rate of change.
tspan: The initial value of the dependent variable (state).
options: Optional parameters for the ODE solver, such as relative tolerance, absolute tolerance, and maximum step size. If not provided, default options will be used.
Returns:
A tuple containing two elements:
ColVec T: A column vector of time points at which the solution was computed.
Matrix Y: A matrix where each row corresponds to the state of the system at the corresponding time point in T.
Remark:
This method uses Adaptive Diagonally Implicit RungeKutta of 4th and 5th Order Method (Ode45i) to solve the ODE. It is an adaptive step size method that adjusts the step size to achieve the desired accuracy.
For best results, the function should be smooth within the integration interval.
Example:
Solve the ODE \(~ty^2y'^3 - y^3y'^2 + t(t^2 + 1)y' - t^2y = 0~\) with initial condition \(~y(0) = \sqrt{1.5}~\).
Fits a polynomial of degree N to the data points specified by the arrays X and Y.
Mathematically, this can be represented as finding the coefficients of the polynomial:
\[P(x) = a_0 + a_1 x + a_2 x^2 + ... + a_N x^N\]
that best fits the given data points (X, Y).
Param:
X: The x-coordinates of the data points.
Y: The y-coordinates of the data points.
N: The degree of the polynomial to fit.
Returns:
An array containing the coefficients of the fitted polynomial, starting with the coefficient of the highest degree term.
Example:
\[X = [1, 2, 3, 4],~ Y = [1, 4, 9, 16],~ N = 2\]
In this example, we fit a polynomial of degree 2 to the data points.
The x-coordinates are represented by the array { 1, 2, 3, 4 } and the y-coordinates by { 1, 4, 9, 16 }.
// import librariesusingSystem;usingSepalSolver.Math;// Example of fitting a polynomialdouble[]X={1,2,3,4};double[]Y={1,4,9,16};intN=2;double[]coefficients=Polyfit(X,Y,N);// Print the resultConsole.WriteLine($"Coefficients: {string.Join(",", coefficients)}");
Coeffs: The coefficients of the polynomial, ordered from the highest degree to the constant term.
Returns:
An array of Complex numbers representing the roots of the polynomial.
Example:
\[P(x) = 2x^5 + 3x^4 + 5x^3 + 2x^2 + 7x + 4\]
In this example, we find the roots of the polynomial represented by the coefficients { 2, 3, 4, 2, 7, 4 }.
// import libraries
using System;
using SepalSolver;
using static SepalSolver.Math;
// Example of finding roots of a polynomial
double[] Coeffs = [2, 3, 4, 2, 7, 4];
Complex[] roots = Roots(Coeffs);
// Print the result
Console.WriteLine($"Roots:\n {string.Join("\n ", roots)}");
In this example, we find the roots of the polynomial with complex coefficients.
// import libraries
using System;
using SepalSolver;
using static SepalSolver.Math;
// Example of finding roots of a polynomial with complex coefficients
Complex[] Coeffs = [new(5, 2), new(3, 7), new(5, 8), new(3, 7), new(7, 4)];
Complex[] roots = Roots(Coeffs);
// Print the result
Console.WriteLine($"Roots:\n {string.Join("\n ", roots)}");
In this example, we perform polynomial deconvolution on two polynomials.
The dividend polynomial is represented by the coefficients { 1, 2, 3, 4, 5, 6 } and the divisor polynomial by { 1, 2, 3 }.
// import librariesusingSystem;usingSepalSolver.Math;// Example of performing polynomial deconvolutiondouble[]Polynomial=[1,2,3,4,5,6];double[]Divisor=[1,2,3];varresult=Deconv(Polynomial,Divisor);// Print the resultConsole.WriteLine($"Quotient: {string.Join(",", result.Quotient)}");Console.WriteLine($"Remainder: {string.Join(",", result.Remainder)}");
Polynomial: The coefficients of the first polynomial.
Multiplier: The coefficients of the second polynomial.
Returns:
An array containing the coefficients of the resulting polynomial.
Example:
\[P(x) = x^2 + 2x + 3,~ M(x) = x + 1\]
In this example, we perform polynomial convolution on two polynomials.
The first polynomial is represented by the coefficients \([1, 2, 3]\) and the second polynomial by \([1, 1]\).
// import librariesusingSystem;usingSepalSolver.Math;// Example of performing polynomial convolutiondouble[]Polynomial=[1,2,3];double[]Multiplier=[1,1];double[]Product=Conv(Polynomial,Multiplier);// Print the resultConsole.WriteLine($"Product: {string.Join(",", Product)}");
In this example, we perform polynomial convolution on two polynomials.
The first polynomial is represented by the coefficients \([2+3i, 5-i, 3+7i]\) and the second polynomial by \([-3+2i, 2-i]\).
// import librariesusingSystem;usingSepalSolver.Math;// Example of performing polynomial convolutionComplex[]Polynomial=[new(2,3),new(5,-1),new(3,7)];Complex[]Multiplier=[new(-3,2),new(2,-1)];varProduct=Conv(Polynomial,Multiplier);// Print the resultConsole.WriteLine($"Product: {string.Join(",", Product)}");
Computes the definite integral of a function using adaptive Gauss-LegendreP quadrature.
Param:
fun: The function to integrate. The function should accept a double and return a double.
x_1: The lower bound of the integration interval.
x_2: The upper bound of the integration interval.
eps: The desired relative accuracy. The default value is 1e-6.
Returns:
The approximate value of the definite integral.
Remark:
This method uses adaptive Gauss-LegendreP quadrature to approximate the definite integral.
The number of quadrature points is increased until the desired relative accuracy is achieved or a maximum number of iterations is reached.
For best results, the function should be smooth within the integration interval.
If x_1 equals x_2 then the method will return 0.
Example:
Integrate the function f(x) = x^2, which can be expressed as:
\[\int_{x_1}^{x_2} x^2 \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double>f=(x)=>x*x;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral(f,x_1,x_2);// Print the resultConsole.WriteLine($"The integral of x^2 is approximately: {integral}");
Output:
The integral of x^2 is approximately: 0.333333333321056
cref=System.ArgumentNullException is Thrown when the fun is null.
cref=System.Exception is Thrown when the maximum number of iterations is reached without achieving the desired accuracy.
Computes the definite integral of a function using adaptive Gauss-LegendreP quadrature.
Param:
fun: The function to integrate. The function should accept a double and return a double.
x_1: The lower bound of the integration interval.
x_2: The upper bound of the integration interval.
eps: The desired relative accuracy. The default value is 1e-6.
Returns:
The approximate value of the definite integral.
Remark:
This method uses adaptive Gauss-LegendreP quadrature to approximate the definite integral.
The number of quadrature points is increased until the desired relative accuracy is achieved or a maximum number of iterations is reached.
For best results, the function should be smooth within the integration interval.
If x_1 equals x_2 then the method will return 0.
Example:
Integrate the function f(x) = x^2, which can be expressed as:
\[\int_{x_1}^{x_2} x^2 \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double>f=(x)=>x*x;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral(f,x_1,x_2);// Print the resultConsole.WriteLine($"The integral of x^2 is approximately: {integral}");
Output:
The integral of x^2 is approximately: 0.333333333321056
cref=System.ArgumentNullException is Thrown when the fun is null.
cref=System.Exception is Thrown when the maximum number of iterations is reached without achieving the desired accuracy.
Computes the definite double integral of a function over a region where both y-bounds are defined by functions of x, using adaptive Gauss-LegendreP quadrature.
Mathematically, this can be represented as:
fun: The function to integrate. The function should accept two doubles (x, y) and return a double.
x_1: The lower bound of the x integration.
x_2: The upper bound of the x integration.
y_1: A function that defines the lower bound of the y integration as a function of x. It should accept a double (x) and return a double (y).
y_2: A function that defines the upper bound of the y integration as a function of x. It should accept a double (x) and return a double (y).
eps: The desired relative accuracy. The default value is 1e-6.
Returns:
The approximate value of the definite double integral.
Remark:
This method uses adaptive Gauss-LegendreP quadrature to approximate the double integral.
The integration is performed over the region defined by x_1 <= x <= x_2 and y_1(x) <= y <= y_2(x).
The number of quadrature points is increased until the desired relative accuracy is achieved or a maximum number of iterations is reached.
For best results, the function should be smooth within the integration region, and both y_1(x) and y_2(x) should be smooth functions. Additionally, y_1(x) should be less than or equal to y_2(x) for all x in the interval [x_1, x_2] to ensure a valid integration region.
If x_1 equals x_2 then the method will return 0.
Example:
Integrate the function f(x, y) = x * y over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), which can be expressed as:
\[\int_{0}^{1} \int_{x^{2}}^{\sqrt{x}} x y \, dy \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double,double>f=(x,y)=>x*y;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral2(f,x_1,x_2,y_1,y_2);// Print the resultConsole.WriteLine($"The integral is approximately: {integral}");
Integrate the function f(x, y) = x * y, which can be expressed as:
\[\int_{0}^{1} \int_{1}^{2} x y \, dy \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double,double>f=(x,y)=>x*y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Set the lower bound of yFunc<double,double>y_1=x=>1;// Set the upper bound of yFunc<double,double>y_2=x=>2;// Calculate the integraldoubleintegral=Integral2(f,x_1,x_2,y_1,y_2);// Print the resultConsole.WriteLine($"The integral of x*y is approximately: {integral}");
Output:
The integral of x*y is approximately: 0.749999999948747
Example:
Integrate the function f(x, y) = x * y over the region where x ranges from 0 to 1, and y ranges from x^2 to 2, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2} x y \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double>f=(x,y)=>x*y;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Set the upper bound of ydoubley_2=2;// Calculate the integraldoubleintegral=Integrators.GaussLeg2(f,x_1,x_2,y_1,y_2);// Print the resultConsole.WriteLine($"The integral is approximately: {integral}");
Output:
The integral is approximately: 0.916666666604556
Example:
Integrate the function f(x, y) = x * y over the region where x ranges from 0 to 1, and y ranges from 1 to x^2, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2(x)} x y \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double>f=(x,y)=>x*y;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>x*x;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Set the lower bound of ydoubley_1=1;// Calculate the integraldoubleintegral=Integrators.GaussLeg2(f,x_1,x_2,y_1,y_2);// Print the resultConsole.WriteLine($"The integral is approximately: {integral}");
Output:
The integral is approximately: -0.166666666655809
Example:
Integrate the function f(x, y) = x * y over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2(x)} x y \, dy \, dx\]
// import librariesusingSepalSolver;usingstaticSystem.MathusingSystem;// Define the function to integrateFunc<double,double,double>f=(x,y)=>x*y;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integrators.GaussLeg2(f,x_1,x_2,y_1,y_2);// Print the resultConsole.WriteLine($"The integral is approximately: {integral}");
Output:
The integral is approximately: 0.0833333333277262
cref=System.ArgumentNullException is Thrown when the fun is null.
cref=System.ArgumentNullException is Thrown when the y_1 is null.
cref=System.ArgumentNullException is Thrown when the y_2 is null.
cref=System.ArgumentException is Thrown when y_1(x) is greater than y_2(x) for any x in the interval [x_1, x_2].
Computes the definite triple integral of a function over a region where the y-bounds are defined by functions of x, and the z-bounds are defined by functions of x and y, using adaptive Gauss-LegendreP quadrature.
Mathematically, this can be represented as:
fun: The function to integrate. The function should accept three doubles (x, y, z) and return a double.
x_1: The lower bound of the x integration.
x_2: The upper bound of the x integration.
y_1: A double or function that defines the lower bound of the y integration as a function of x. It should accept a double (x) and return a double (y).
y_2: A double or function that defines the upper bound of the y integration as a function of x. It should accept a double (x) and return a double (y).
z_1: A double or function that defines the lower bound of the z integration as a function of x and y. It should accept two doubles (x, y) and return a double (z).
z_2: A double or function that defines the upper bound of the z integration as a function of x and y. It should accept two doubles (x, y) and return a double (z).
eps: The desired relative accuracy. The default value is 1e-6.
Returns:
The approximate value of the definite triple integral.
Remark:
This method uses adaptive Gauss-LegendreP quadrature to approximate the triple integral.
The integration is performed over the region defined by x_1 <= x <= x_2, y_1(x) <= y <= y_2(x), and z_1(x, y) <= z <= z_2(x, y).
The number of quadrature points is increased until the desired relative accuracy is achieved or a maximum number of iterations is reached.
For best results, the function should be smooth within the integration region, y_1(x), y_2(x), z_1(x, y), and z_2(x, y) should be smooth functions.
Ensure that y_1(x) <= y_2(x) and z_1(x, y) <= z_2(x, y) throughout the integration region.
If x_1 equals x_2 then the method will return 0.
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from 1 to 2, and z ranges from 2 to 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2} x y z \, dz \, dy \, dx\]
// import librariesusingSystem;usingSepalSolver;usingstaticSepalSolver.Math;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Set the lower bound of ydoubley_1=1;// Set the upper bound of ydoubley_2=2;// Set the lower bound of zdoublez1=2;// Set the upper bound of zdoublez2=3;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z1,z2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 1.8749999998078
<example>
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), and z ranges from 2 to 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2(x)} \int_{z_1}^{z_2} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingstaticSystem.MathusingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Set the lower bound of zdoublez_1=2;// Set the upper bound of zdoublez_2=3;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 0.208333333312197
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from 1 to x^2, and z ranges from 2 to 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2(x)} \int_{z_1}^{z_2} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>x*x;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Set the lower bound of ydoubley_1=1;// Set the lower bound of zdoublez_1=2;// Set the upper bound of zdoublez_2=3;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: -0.416666666625285
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to 2, and z ranges from 2 to 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2} \int_{z_1}^{z_2} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Set the upper bound of ydoubley_2=2;// Set the lower bound of zdoublez_1=2;// Set the upper bound of zdoublez_2=3;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 2.29166666643309
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), and z ranges from x*y to x+y, which can be expressed as:
\[\int_{0}^{1} \int_{x^{2}}^{\sqrt{x}} \int_{xy}^{x+y} x y z \, dz \, dy \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 0.0641203694008985
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to 2, and z ranges from x*y to x+y, which can be expressed as:
\[\int_{0}^{1} \int_{x^{2}}^{2} \int_{xy}^{x+y} x y z \, dz \, dy \, dx\]
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Set the upper bound of yFunc<double,double>y_2=(x)=>2;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 1.56851851820977
Example:
Integrate the function f(x, y, z) = x * x * y * y * z over the region where x ranges from -1 to 1, y ranges from -1 to 1, and z ranges from x*y to 2, which can be expressed as:
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*x*y*y*z;// Set the lower bound of ydoubley_1=-1;// Set the upper bound of ydoubley_2=1;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Set the upper bound of zdoublez_2=2;// Set the lower bound of xdoublex_1=-1;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x^2*y^2*z is approximately: {integral}");
Output:
The triple integral of x^2*y^2*z is approximately: 0.808888888786791
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to 2, and z ranges from x*y to 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2} \int_{z_1(x,y)}^{z_2} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Set the upper bound of ydoubley_2=2;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Set the upper bound of zdoublez_2=3;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 3.63541666602461
Example:
Integrate the function f(x, y, z) = x + y + z over the region where x ranges from 0 to 1, y ranges from 1 to x + 2, and z ranges from x*y to 4, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2(x)} \int_{z_1(x, y)}^{z_2} (x + y + z) \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x+y+z;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>x+2;// Set the lower bound of ydoubley_1=1;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Set the upper bound of zdoublez_2=4;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x+y+z is approximately: {integral}");
Output:
The triple integral of x+y+z is approximately: 20.7166666645573
Example:
Integrate the function f(x, y, z) = x * x + y * y + z * z over the region where x ranges from 0 to 1, y ranges from 0 to sqrt(x), and z ranges from x+y to 5, which can be expressed as:
// import librariesusingSepalSolver;usingstaticSystem.MathusingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*x+y*y+z*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>0;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x+y;// Set the upper bound of zdoublez_2=5;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x^2+y^2+z^2 is approximately: {integral}");
Output:
The triple integral of x^2+y^2+z^2 is approximately: 29.0252572989997
Example:
Integrate the function f(x, y, z) = 1 / (1 + x + y + z) over the region where x ranges from 0 to 1, y ranges from 0 to 2, and z ranges from 1 to x*x + y*y + 3, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2(x, y)} \frac{1}{1 + x + y + z} \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>1.0/(1.0+x+y+z);// Set the lower bound of ydoubley_1=0;// Set the upper bound of ydoubley_2=2;// Set the lower bound of zdoublez_1=1;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x*x+y*y+3;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of 1/(1+x+y+z) is approximately: {integral}");
Output:
The triple integral of 1/(1+x+y+z) is approximately: 1.40208584910316
Example:
Integrate the function f(x, y, z) = x * y + z over the region where x ranges from 0 to 2, y ranges from sin(x) to 3, and z ranges from -1 to x*x + y + 2, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2} \int_{z_1}^{z_2(x, y)} (x y + z) \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y+z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>Sin(x);// Set the upper bound of ydoubley_2=3;// Set the lower bound of zdoublez_1=-1;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x*x+y+2;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=2;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of xy+z is approximately: {integral}");
Output:
The triple integral of xy+z is approximately: 119.271742284841
Example:
Integrate the function f(x, y, z) = x - y + 2*z over the region where x ranges from 1 to 3, y ranges from -2 to x*x, and z ranges from 0 to x + y + 1, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2(x)} \int_{z_1}^{z_2(x, y)} (x - y + 2z) \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x-y+2*z;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>x*x;// Set the lower bound of ydoubley_1=-2;// Set the lower bound of zdoublez_1=0;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y+1;// Set the lower bound of xdoublex_1=1;// Set the upper bound of xdoublex_2=3;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x-y+2z is approximately: {integral}");
Output:
The triple integral of x-y+2z is approximately: 353.666666629263
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), and z ranges from 2 to x+y, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2(x)} \int_{z_1}^{z_2(x,y)} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingstatiSystem.Math;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Set the lower bound of zdoublez_1=2;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: -0.0921296305735099
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from 1 to 2, and z ranges from x*y to x+y, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1(x,y)}^{z_2(x,y)} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Set the lower bound of ydoubley_1=1;// Set the upper bound of ydoubley_2=2;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 1.43402777762941
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to 2, and z ranges from x*y to x+y, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2} \int_{z_1(x,y)}^{z_2(x,y)} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Set the upper bound of ydoubley_2=2;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 1.56851851820977
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from 1 to x^2, and z ranges from x*y to x+y, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1}^{y_2(x)} \int_{z_1(x,y)}^{z_2(x,y)} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>x*x;// Set the lower bound of ydoubley_1=1;// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: -0.134490740716508
Example:
Integrate the function f(x, y, z) = x * y * z over the region where x ranges from 0 to 1, y ranges from x^2 to sqrt(x), and z ranges from x*y to x+y, which can be expressed as:
\[\int_{x_1}^{x_2} \int_{y_1(x)}^{y_2(x)} \int_{z_1(x,y)}^{z_2(x,y)} x y z \, dz \, dy \, dx\]
// import librariesusingSepalSolver;usingstaticSystem.Math;usingSystem;// Define the function to integrateFunc<double,double,double,double>f=(x,y,z)=>x*y*z;// Define the lower bound of y as a function of xFunc<double,double>y_1=(x)=>x*x;// Define the upper bound of y as a function of xFunc<double,double>y_2=(x)=>Sqrt(x);// Define the lower bound of z as a function of x and yFunc<double,double,double>z_1=(x,y)=>x*y;// Define the upper bound of z as a function of x and yFunc<double,double,double>z_2=(x,y)=>x+y;// Set the lower bound of xdoublex_1=0;// Set the upper bound of xdoublex_2=1;// Calculate the integraldoubleintegral=Integral3(f,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The triple integral of x*y*z is approximately: {integral}");
Output:
The triple integral of x*y*z is approximately: 0.0641203694008985
cref=System.ArgumentNullException is Thrown when the fun is null.
cref=System.ArgumentNullException is Thrown when the y_1 is null.
cref=System.ArgumentNullException is Thrown when the y_2 is null.
cref=System.ArgumentNullException is Thrown when the z_1 is null.
cref=System.ArgumentNullException is Thrown when the z_2 is null.
cref=System.Exception is Thrown when the maximum number of iterations is reached without achieving the desired accuracy.
Computes the definite quadruple integral of a function over a region where the y-bounds are defined by functions of x, and the z-bounds are defined by functions of x and y, using adaptive Gauss-LegendreP quadrature.
Param:
fun: The function to integrate. The function should accept four doubles (w, x, y, z) and return a double.
w_1: The lower bound of the w integration.
w_2: The upper bound of the w integration.
x_1: A function that defines the lower bound of the x integration as a function of w. It should accept a double (w) and return a double (x).
x_2: A function that defines the upper bound of the x integration as a function of w. It should accept a double (w) and return a double (x).
y_1: A function that defines the lower bound of the y integration as a function of w and x. It should accept two doubles (w, x) and return a double (y).
y_2: A function that defines the upper bound of the y integration as a function of w and x. It should accept two doubles (w, x) and return a double (y).
z_1: A function that defines the lower bound of the z integration as a function of w, x and y. It should accept three doubles (w, x, y) and return a double (z).
z_2: A function that defines the upper bound of the z integration as a function of w, x and y. It should accept three doubles (w, x, y) and return a double (z).
eps: The desired relative accuracy. The default value is 1e-6.
Returns:
The approximate value of the definite triple integral.
Remark:
This method uses adaptive Gauss-LegendreP quadrature to approximate the quadruple integral.
The integration is performed over the region defined by w_1 <= w <= w_2, x_1(w) <= x <= x_2(w), y_1(w, x) <= y <= y_2(w, x), and z_1(w, x, y) <= z <= z_2(w, x, y).
The number of quadrature points is increased until the desired relative accuracy is achieved or a maximum number of iterations is reached.
For best results, the function should be smooth within the integration region, x_1(w), x_2(w), y_1(w, x), y_2(w, x), z_1(w, x, y), and z_2(w, x, y) should be smooth functions.
Ensure that x_1(w) <= x_2(w), y_1(w, x) <= y_2(w, x) and z_1(w, x, y) <= z_2(w, x, y) throughout the integration region.
If x_1 equals x_2 then the method will return 0.
Example:
To compute the volume of a sphere in 4D: \(f(w, x, y, z) = 1\) over the region where w ranges from -1 to 1, x ranges from \(-\sqrt{1-w^2}\) to \(\sqrt{1-w^2}\), y ranges from \(-\sqrt{1-w^2-x^2}\) to \(\sqrt{1-w^2-x^2}\), and z ranges from \(-\sqrt{1-w^2-x^2-y^2}\) to \(\sqrt{1-w^2-x^2-y^2}\), which can be expressed as:
// import librariesusingSystem;usingSepalSolver.Math;// Define the function to integrateFunc<double,double,double,double,double>f=(w,x,y,z)=>1;// Define the lower bound of z as a function of x and yFunc<double,double,double,double>z_1=(w,x,y)=>-Sqrt(1-w*w-x*x-y*y);// Define the upper bound of z as a function of x and yFunc<double,double,double,double>z_2=(w,x,y)=>Sqrt(1-w*w-x*x-y*y);// Define the lower bound of y as a function of xFunc<double,double,double>y_1=(w,x)=>-Sqrt(1-w*w-x*x);// Define the upper bound of y as a function of xFunc<double,double,double>y_2=(w,x)=>Sqrt(1-w*w-x*x);// Define the lower bound of x as a function of wFunc<double,double>x_1=(w)=>-Sqrt(1-w*w);// Define the upper bound of x as a function of wFunc<double,double>x_2=(w)=>Sqrt(1-w*w);// Set the lower bound of wdoublew_1=-1;// Set the upper bound of wdoublew_2=1;// Calculate the integraldoubleintegral=Integral4(f,w_1,w_2,x_1,x_2,y_1,y_2,z_1,z_2);// Print the resultConsole.WriteLine($"The approximate volume of a 4D sphere: {integral}");Console.WriteLine($"The exact volume of a 4D sphere: {pi*pi/2}");
Output:
The approximate volume of a 4D sphere: 4.93483151454187
The exact volume of a 4D sphere: 4.93480220054468
cref=System.ArgumentNullException is Thrown when the fun is null.
cref=System.ArgumentNullException is Thrown when the x_1 is null.
cref=System.ArgumentNullException is Thrown when the x_2 is null.
cref=System.ArgumentNullException is Thrown when the y_1 is null.
cref=System.ArgumentNullException is Thrown when the y_2 is null.
cref=System.ArgumentNullException is Thrown when the z_1 is null.
cref=System.ArgumentNullException is Thrown when the z_2 is null.
cref=System.Exception is Thrown when the maximum number of iterations is reached without achieving the desired accuracy.