Java - Computation of Derivations with Apache Commons Mathematic Library - java

I have a problem in using the apache commons math library.
I just want to create functions like f(x) = 4x^2 + 2x and I want to compute the derivative of this function --> f'(x) = 8x + 2
I read the article about Differentiation (http://commons.apache.org/proper/commons-math/userguide/analysis.html, section 4.7).
There is an example which I don't understand:
int params = 1;
int order = 3;
double xRealValue = 2.5;
DerivativeStructure x = new DerivativeStructure(params, order, 0, xRealValue);
DerivativeStructure y = f(x); //COMPILE ERROR
System.out.println("y = " + y.getValue();
System.out.println("y' = " + y.getPartialDerivative(1);
System.out.println("y'' = " + y.getPartialDerivative(2);
System.out.println("y''' = " + y.getPartialDerivative(3);
In Line 5 a compile error occurs of course. The function f(x) is called and not defined. What I am getting wrong?
Has anyone any experience with the differentiation/derivation with the apache commons math library or does anyone know another library/framework which can help me?
Thanks

In the paragraph below that example, the author describes ways to create DerivativeStructures. It isn't magic. In the example you quoted, someone was supposed to write the function f. Well, that wasn't very clear.
There are several ways a user can create an implementation of the UnivariateDifferentiableFunction interface. The first method is to simply write it directly using the appropriate methods from DerivativeStructure to compute addition, subtraction, sine, cosine... This is often quite straigthforward and there is no need to remember the rules for differentiation: the user code only represent the function itself, the differentials will be computed automatically under the hood. The second method is to write a classical UnivariateFunction and to pass it to an existing implementation of the UnivariateFunctionDifferentiator interface to retrieve a differentiated version of the same function. The first method is more suited to small functions for which user already control all the underlying code. The second method is more suited to either large functions that would be cumbersome to write using the DerivativeStructure API, or functions for which user does not have control to the full underlying code (for example functions that call external libraries).
Use the first idea.
// Function of 1 variable, keep track of 3 derivatives with respect to that variable,
// use 2.5 as the current value. Basically, the identity function.
DerivativeStructure x = new DerivativeStructure(1, 3, 0, 2.5);
// Basically, x --> x^2.
DerivativeStructure x2 = x.pow(2);
//Linear combination: y = 4x^2 + 2x
DerivativeStructure y = new DerivativeStructure(4.0, x2, 2.0, x);
System.out.println("y = " + y.getValue());
System.out.println("y' = " + y.getPartialDerivative(1));
System.out.println("y'' = " + y.getPartialDerivative(2));
System.out.println("y''' = " + y.getPartialDerivative(3));

The following thread from the Apache mailing list seems to illustrate the two possible ways of how the derivative of a UnivariateDifferentiableFunction can be defined. I am adding a new answer as I'm unable to comment on the previous one (insufficient reputation).
The used sample specification of the function is f(x) = x^2.
(1) Using a DerivativeStructure:
public DerivativeStructure value(DerivativeStructure t) {
return t.multiply(t);
}
(2) By writing a classical UnivariateFunction:
public UnivariateRealFunction derivative() {
return new UnivariateRealFunction() {
public double value(double x) {
// example derivative
return 2.*x;
}
}
}
If I understand well, the advantage of the first case is that the derivative does not need to be obtained manually, as in the second case. In case the derivative is known, there should thus be no advantage of defining a DerivativeStructure, right? The application I have in mind is that of a Newton-Raphson solver, for which generally the function value and its derivative need to be known.
The full example is provided on the aforementioned web site (authors are Thomas Neidhart and Franz Simons). Any further comments are most welcome!

Related

How to access the final simplex tableau in CPLEX?

I'm solving a LP with CPLEX using the Java API. I build my model with the methods provided (like cplex.numVar(col, lb, ub) and cplex.addLe()) After optimization is done, I'm interested in reading the simplex tableau of the final iteration (to be precise: not only the duals and reduced costs but also the coefficients inside the tableau).
I tried to access the IloLPMatrix object cplex.LPMatrix(), but this only returns an empty matrix. I'm interested in the "filled" matrix associated to the problem I just solved.
So, how can I read the simplex tableau?
The short answer is that you cannot access the simplex tableau with the Concert (Java/.NET/C++) APIs. You can access this advanced feature with the C Callable Library and Python APIs, though. For example, see CPXXbinvarow and examining the simplex tableau in the Python API.
Now, to clear up your possible confusion with what IloLPMatrix does, consider the following (mostly cribbed from this thread on the official IBM developerWorks forum).
If you add constraints to the model with cplex.addLe() then you can use rangeIterator to access them (and possibly conversionIterator, SOS1Iterator, SO2Iterator). Note that when you use rangeIterator you have to figure out the runtime type of an expression before you can get at the coefficients. For example:
for (Iterator it = cplex.rangeIterator(); it.hasNext(); /* nothing */) {
IloRange range = (IloRange)it.next();
IloNumExpr expr = range.getExpr(); // Cannot get the coefficients of expr directly :-(
if (expr instanceof IloLinearNumExpr) {
IloLinearNumExpr linExpr = (IloLinearNumExpr)expr;
for (IloLinearNumExprIterator jt = linExpr.linearIterator(); jt.hasNext(); /* nothing */) {
IloNumVar var = jt.nextNumVar();
double coef = jt.getValue();
...
}
}
else if (expr instance of ...) {
...
}
}
On the other hand, if you build your model with an IloLPMatrix, then you can access it with LPMatrixIterator. When you call cplex.LPMatrix it "Creates and returns an empty LP matrix object." You then have to fill it and add it to the model. Alternately, you can use addLPMatrix to create and add it in one step (you still need to populate it).
For example:
// Create a matrix in which we setup the model.
IloLPMatrix matrix = cplex.LPMatrix();
// Create variables.
IloNumVar x = cplex.numVar();
IloNumVar y = cplex.numVar();
matrix.addCols(new IloNumVar[]{ x, y });
// Create constraint x + y <= 2.
IloLinearNumExpr lhs = cplex.linearNumExpr();
lhs.addTerm(x, 1.0);
lhs.addTerm(y, 1.0);
matrix.addRow(cplex.le(lhs, 2.0));
// When all constraints are setup add the matrix to the model.
cplex.add(matrix);
Note that you can only add linear constraints when using an IloLPMatrix.
Whether you use the first method to build your model and rangeIterator to access it, or the second method and LPMatrixIterator, is a matter of taste and possibly some performance trade-offs; you'd have to experiment with both approaches.
In CPLEX_Studio128\cplex\examples\src\java you could have a look at the example LPex1.java.

Evaluating trigonometric expressions in Java

How to insert a trigonometric function in the console for further work with it?? For example, sin(x) = 2x + 3log (y) or something like this.I think.. I need to enter an expression as a string, and then it is processed as. But how?
Take a look at exp4j
We have used this library extensively in one of our projects for solving the exact same problem that you are facing.
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
In your particular case, you can ask the user for the following inputs in the console and build your expression using these inputs :
Enter the expression to evaluate. This will become the argument to the ExpressionBuilder constructor.
Enter the Strings that represent the variables in the expression. This will become the input to the variables method. You can add these Strings as keys to a Map which can be used in the next step.
Enter the value of each variable. This will become the input to the setVariable methods. You could collect all the variable values as values in the Map created in the above step. You can iterate over the map and call setVariable(key,value) so that you don't need to know how many variables are present in an expression before hand.
Try exp4j. Example(from the link):
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Another option is Javaluator. See the link for example.
And there's EvalX. See below example(from the link):
Expression expression = new Expression("1+1/3");
result = expression.eval():
expression.setPrecision(2);
result = expression.eval():
I hope this helps!
Just an addition, I recently found out you can separate exp4j ExpressionBuilder into two parts and add values to the variables in a for loop, you can find may examples at this website https://github.com/fasseg/exp4j/blob/master/src/test/java/net/objecthunter/exp4j/ExpressionBuilderTest.java
ExpressionBuilder e = new ExpressionBuilder("x^2")
.variable("x")
.build();
for(int i = 0; i < 10; i++) {
e.setVariable("x", i);
System.out.println("x^2 = " + e.evaluate());
}

Java: calculating velocity of a skydiver

In Java, I am trying to implement the following equation for calculating the current velocity of a skydiver not neglecting air resistance.
v(t) = v(t-∆t) + (g - [(drag x crossArea x airDensity) / (2*mass)] *
v[(t-∆t)^2] ) * (∆t)
My problem is that I am not sure how to translate "v(t - ∆t)" into a code. Right now I have this method below, where as you can see I am using the method within itself to find the previous velocity. This has continued to result in a stack overflow error message, understandably.
(timeStep = ∆t)
public double calculateVelocity(double time){
double velocity;
velocity = calculateVelocity(time - timeStep)
+ (acceleration - ((drag * crossArea * airDensity)
/ (2 * massOfPerson))
* (calculateVelocity(time - timeStep)*(time * timeStep)))
* timeStep;
}
return velocity;
}
I am calling the above method in the method below. Assuming that the ending time = an int, will be the user input but written this way to be dynamic.
public void assignVelocitytoArrays(){
double currentTime = 0;
while(currentTime <= endingTime){
this.vFinal = calculateVelocity(currentTime);
currentTime += timeStep;
}
}
I would like to figure this out on my own, could someone give me a general direction? Is using a method within itself the right idea or am I completely off track?
The formula you want to implement is the recursive representation of a sequence, mathematiacally speaking.
Recursive sequences need a starting point, e.g.
v(0) = 0 (because a negative time does not make sense)
and a rule to calculate the next elements, e.g.
v(t) = v(t-∆t) + (g - [(drag x crossArea x airDensity) / (2*mass)] * v[(t-∆t)^2] ) * (∆t)
(btw: are you sure it has to be v([t-∆t]^2) instead of v([t-∆t])^2?)
So your approach to use recursion (calling a function within itself) to calculate a recursive sequence is correct.
In your implementation, you only forgot one detail: the starting point. How should your program know that v(0) is not defined be the rule, but by a definite value? So you must include it:
if(input value == starting point){
return starting point
}
else{
follow the rule
}
On a side note: you seem to be creating an ascending array of velocities. It would make sense to use the already calculated values in the array instead of recursion, so you don't have to calculate every step again and again.
This only works if you did indeed make a mistake in the rule.
double[] v = new double[maxTime/timeStep];
v[0] = 0; //starting point
for(int t = 1; t < maxSteps; t++){
v[t] = v[t-1] + (g - [(drag x crossArea x airDensity) / (2*mass)] * v[t-1]^2 ) * (∆t)
}

Using of getSpectrum() in Libgdx library

I know the first thing you are thinking is "look for it in the documentation", however, the documentation is not clear about it.
I use the library to get the FFT and I followed this short guide:
http://www.digiphd.com/android-java-reconstruction-fast-fourier-transform-real-signal-libgdx-fft/
The problem arises when it uses:
fft.forward(array);
fft_cpx=fft.getSpectrum();
tmpi = fft.getImaginaryPart();
tmpr = fft.getRealPart();
Both "fft_cpx", "tmpi", "tmpr" are float vectors. While "tmpi" and "tmpr" are used for calculate the magnitude, "fft_cpx" is not used anymore.
I thought that getSpectrum() was the union of getReal and getImmaginary but the values are all different.
Maybe, the results from getSpectrum are complex values, but what is their representation?
I tried without fft_cpx=fft.getSpectrum(); and it seems to work correctly, but I'd like to know if it is actually necessary and what is the difference between getSpectrum(), getReal() and getImmaginary().
The documentation is at:
http://libgdx-android.com/docs/api/com/badlogic/gdx/audio/analysis/FFT.html
public float[] getSpectrum()
Returns: the spectrum of the last FourierTransform.forward() call.
public float[] getRealPart()
Returns: the real part of the last FourierTransform.forward() call.
public float[] getImaginaryPart()
Returns: the imaginary part of the last FourierTransform.forward()
call.
Thanks!
getSpectrum() returns absolute values of complex numbers.
It is calculated like this
for (int i = 0; i < spectrum.length; i++) {
spectrum[i] = (float)Math.sqrt(real[i] * real[i] + imag[i] * imag[i]);
}

Inverse Logistic Function / Reverse Sigmoid Function

I am currently coding up a fuzzy logic library in java. I have found the equations for all the standard functions - Grade, inverseGrade, Triangle, Trapezoid, Gaussian. However, I can't find the inverse of the sigmoid/ logistic function.
The way I have written the logistic function is java is :
//f(x) = 1/(1+e(-x))
public double logistic(double x){
return (1/(1+(Math.exp(-x)));
}
But I can't work out or find the inverse anywhere.
My algebraic/calculus abilities are fairly limited, hence why I haven't been able to work out the inverse of the function.
Any hints or pointers would be a big help.
Thanks
If
y = 1/(1+exp(-x))
then
x = ln(y/(1-y))
Just to go through the steps:
y = 1/(1 + exp(-x))
1 + exp(-x) = 1/y
exp(-x) = 1/y - 1
exp(-x) = 1/y - y/y
exp(-x) = (1 - y)/y
ln(exp(-x)) = ln((1 - y)/y)
-x = ln((1 - y)/y)
x = -ln((1 - y)/y)
x = ln(y/(1 - y))

Categories

Resources