How to Solve Equations with java? - java

I have three equations like the following ones:
x + y + z = 100;
x + y - z = 50;
x - y - z = 10;
How can I find the values of x, y, and z with Java?
String equation1="x+y+z=100;";
String equation2="x+y-z=50;";
String equation3="x-y-z=10;";
int[] SolveEquations(equation1,equation2,equation3) {
// to do
// how to do?
}
Do you have any possible solutions or other common frameworks?

You can use determinant to calculate values of x y and z.
Logic can be found out here http://www.intmath.com/Matrices-determinants/1_Determinants.php
And then you need to implement it in java using 3 dimensional arrays.

Since you're writing Java, you can use the JAMA package to solve this. I'd recommend a good LU decomposition method.
It's a simple linear algebra problem. You should be able to solve it by hand or using something like Excel pretty easily. Once you have that you can use the solution to test your program.
There's no guarantee, of course, that there is a solution. If your matrix is singular, that means there is no intersection of those three lines in 3D space.

you can use the java matrix package JAMA. See the full page of this example below here
/*
*Solving three variable linear equation system
* 3x + 2y - z = 1 ---> Eqn(1)
* 2x - 2y + 4z = -2 ---> Eqn(2)
* -x + y/2- z = 0 ---> Eqn(3)
*/
import Jama.Matrix;
import java.lang.Math.*;
public class Main {
public Main() {
//Creating Arrays Representing Equations
double[][] lhsArray = {{3, 2, -1}, {2, -2, 4}, {-1, 0.5, -1}};
double[] rhsArray = {1, -2, 0};
//Creating Matrix Objects with arrays
Matrix lhs = new Matrix(lhsArray);
Matrix rhs = new Matrix(rhsArray, 3);
//Calculate Solved Matrix
Matrix ans = lhs.solve(rhs);
//Printing Answers
System.out.println("x = " + Math.round(ans.get(0, 0)));
System.out.println("y = " + Math.round(ans.get(1, 0)));
System.out.println("z = " + Math.round(ans.get(2, 0)));
}
public static void main(String[] args) {
new Main();
}
}

You can also use Commons Math. They have a section of this in their userguide (see 3.4)

Create a parser using ANTLR. Then evaluate the AST using Gaussian elimination.

Use Gaussian_elimination it's incredibly easy, but there are some values you may have hard life calculating.
Code example

try this, please:
import org.apache.commons.math3.linear.*;
import org.junit.Assert;
import org.junit.Test;
/**
* Author: Andrea Ciccotta
*/
public class LinearSystemTest extends Assert {
/**
* Ax = B
* 2x + 3y - 2z = 1
* -x + 7y + 6x = -2
* 4x - 3y - 5z = 1
* <p>
* it will use the LUDecomposition:
* LU decomposition:
* 1. find A = LU where LUx = B
* 2. solve Ly = B
* 4. solve Ux = y
*/
#Test
public void linearSystem3x3Test() {
final RealMatrix coefficients = new Array2DRowRealMatrix(new double[][]{{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}});
final DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
final RealVector constants = new ArrayRealVector(new double[]{1, -2, 1}, false);
final RealVector solution = solver.solve(constants);
final double[] arraySolution = solution.toArray();
assertEquals(arraySolution[0], -0.36986301369863006, 0);
assertEquals(arraySolution[1], 0.1780821917808219, 0);
assertEquals(arraySolution[2], -0.6027397260273972, 0);
}
}

There are many ways to solve linear system equations. There is a simplest way to perform this. In the example the java code solve for two variables USING Matrix method but you can modify to perform 3 variables calculations.
import java.util.Scanner; //OBJETO SCANNER
public class SYS2 {
public static void main (String args[]) {
//VARIABLE DECLARATION SPACE
int i=0,j = 0;
float x,y;
Scanner S = new Scanner (System.in);
int EC3[][]= new int [2][3]; //ARRAY TO STORE EQUATION 2X3
float DET1=0;
float DET2 =0;
float DETA=0;
float DETB=0;
//END VARIABLE DECLARATIONS
System.out.println("Enter Equation System : ");
for (i=0; i< 2; i++) {
for (j=0; j< 3; j++)
EC3[i][j] = S.nextInt();
}
System.out.println("SISTEMA DE ECUACION LINEAL: "); //THIS SENTENCE ONLY PRINT THE CATCHED VALUES OF EQUATION
for (i=0; i< 2; i++) {
for (j=0; j< 3; j++)
System.out.print(EC3[i][j] + " ");
System.out.println();
}
// System.out.print("Determinante A de la Matriz: ");
// System.out.print((EC3[0][2] * EC3[1][1]) - (EC3[0][1]*EC3[1][2]) );
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DET1= ((EC3[0][2] * EC3[1][1]) -( EC3[0][1]*EC3[1][2]));
}
// System.out.print(DET1 );
// System.out.println();
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DET2= ((EC3[0][0] * EC3[1][1]) - (EC3[0][1]*EC3[1][0]));
}
// System.out.print("Determinante B de la Matriz: ");
// System.out.println(DET2 );
x = (DET1 / DET2);
System.out.println();
System.out.println("X = " + x);
System.out.print("=======================");
//FIN PARA VALOR DE X
//COMIENZO DE VALOR DE Y
// System.out.print("Determinante A de la Matriz Y: ");
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DETA= EC3[0][0] * EC3[1][2] - EC3[0][2]*EC3[1][0];
// System.out.print(DETA );
// System.out.println();
}
for (i=0;i<2;i++) {
for (j=0; j<2;j++)
DETB= EC3[0][0] * EC3[1][1] - EC3[0][1]*EC3[1][0];
}
// System.out.print("Determinante B de la Matriz Y: ");
// System.out.println(DETB );
y = DETA / DETB;
System.out.print("=======================");
System.out.println();
System.out.println("Y = " + y);
System.out.print("=======================");
}
}

Related

How to get a minimum value that solve a system of inequalities?

I have searched about in here but it loses all sense when I try to implement LP in Java with JOptimizer library,
I need to find a way to solve this simple inequality:
x*k+y*k'>0
with:
1>=x>=0
1>=y>=0
Where k and k' are given constants.
What is the best way to solve this?
Can anyone help me to solve my problem?
Seems you don't have the idea about linear programming. Please Read about it. Here is the answer you asked for.
import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
import com.joptimizer.optimizers.PrimalDualMethod;
/**
*
* #author K.P.L.Kanchana
*/
public class Demo {
public static void main(String[] args){
// BasicConfigurator.configure(); // uncomment and see the console log4j:WARN
// setting value for k as k1 variable
double k1 = 100.2;
// setting value for k' as k2 variable
double k2 = 30.4;
// Objective function (plane)
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {-k1, -k2}, 0); // Maximize kX + K'X
//inequalities (polyhedral feasible set G.X<H )
ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];
// x > 0 ('<=' constraints not applicable in JOptimizer)
inequalities[0] = new LinearMultivariateRealFunction(new double[] {-1, 0}, 0); // -x > o
// y > 0 ('<=' constraints not applicable in JOptimizer)
inequalities[1] = new LinearMultivariateRealFunction(new double[] {0, -1}, 0); // -y > o
// x < 1 ('<=' constraints not applicable in JOptimizer)
inequalities[2] = new LinearMultivariateRealFunction(new double[] {1, 0}, -1); // x-1 < o
// y < 1 ('<=' constraints not applicable in JOptimizer)
inequalities[3] = new LinearMultivariateRealFunction(new double[] {0, 1}, -1); // y-1 < o
//optimization problem
OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
or.setToleranceFeas(JOptimizer.DEFAULT_FEASIBILITY_TOLERANCE);
or.setTolerance(JOptimizer.DEFAULT_TOLERANCE);
//optimization
PrimalDualMethod opt = new PrimalDualMethod();
opt.setOptimizationRequest(or);
try {
int returnCode = opt.optimize();
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
// get the solution
double[] sol = opt.getOptimizationResponse().getSolution();
// display the solution
System.out.println("X = " + sol[0]);
System.out.println("X = " + sol[1]);
}
}

Manual list shuffling in Java produces same result each time

I am trying to create a method for shuffling a list manually. The list is shuffled, but the same result is produced every time. Code example below:
package ch11;
import java.util.ArrayList;
import java.util.Arrays;
public class Chapter_11_E07_ShuffleArrayList {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8};
ArrayList<Integer> intList = new ArrayList<>(Arrays.asList(array));
System.out.println("Before shuffle: ");
for (Integer x: intList)
System.out.print(x + " ");
shuffle(intList);
System.out.println("\nAfter shuffle: ");
for (Integer x: intList)
System.out.print(x + " ");
}
public static void shuffle(ArrayList<Integer> intList) {
// Simple solution
// java.util.Collections.shuffle(intList);
// Manual shuffle
for (Integer x: intList) {
int newIndex = (int) Math.random() * intList.size();
Integer temp = intList.get(x);
intList.set(x, intList.get(newIndex));
intList.set(newIndex, temp);
}
}
}
It seems to work to some extent, but is Math.random * intList.size() producing the same random index every time? Inputs are highly appreciated!
This is because
int newIndex = (int) Math.random() * intList.size();
is not parenthesized properly. It should be
int newIndex = (int)(Math.random() * intList.size());
To avoid simple errors like this, make new Random object, and call nextInt(intList.size()).
To show what I've meant in the comments above, here the code:
for (Integer x: intList) {
int newIndex = (int) (Math.random() * intList.size());
int oldIndex = intList.indexOf(x);
Integer temp = intList.get(newIndex);
intList.set(newIndex, x);
intList.set(oldIndex, temp);
}

java OpenCV find k nearest neighbor c++ to java conversion

I am trying to find the k nearest neighbors with the Knn classifier in OpenCV.
I found this C++ Code:
class atsKNN{
public :
void knn(cv::Mat& trainingData, cv::Mat& trainingClasses, cv::Mat& testData, cv::Mat& testClasses, int K)
{
cv::KNearest knn(trainingData, trainingClasses, cv::Mat(), false, K);
cv::Mat predicted(testClasses.rows, 1, CV_32F);
for(int i = 0; i < testData.rows; i++) {
const cv::Mat sample = testData.row(i);
predicted.at<float>(i,0) = knn.find_nearest(sample, K);
}
float percentage = evaluate(predicted, testClasses) * 100;
cout << "K Nearest Neighbor Evaluated Accuracy = " << percentage << "%" << endl;
prediction = predicted;
}
void showplot(cv::Mat testData)
{
plot_binary(testData, prediction, "Predictions Backpropagation");
}
private:
cv::Mat prediction;
};
The comments mention it works really good but i am having problems Converting it to Java. There is no Documentation for Java. I tried using a C++ to Java Converter but the resulting Code does not work.
here is the code it produced:
public class atsKNN
{
public final void knn(cv.Mat trainingData, cv.Mat trainingClasses, cv.Mat testData, cv.Mat testClasses, int K)
{
cv.KNearest knn = new cv.KNearest(trainingData, trainingClasses, cv.Mat(), false, K);
cv.Mat predicted = new cv.Mat(testClasses.rows, 1, CV_32F);
for (int i = 0; i < testData.rows; i++)
{
final cv.Mat sample = testData.row(i);
predicted.<Float>at(i,0) = knn.find_nearest(sample, K);
}
float percentage = evaluate(predicted, testClasses) * 100;
System.out.print("K Nearest Neighbor Evaluated Accuracy = ");
System.out.print(percentage);
System.out.print("%");
System.out.print("\n");
prediction = predicted;
}
public final void showplot(cv.Mat testData)
{
plot_binary(testData, prediction, "Predictions Backpropagation");
}
private cv.Mat prediction = new cv.Mat();
}
edit:
The line predicted.at(i,0) = knn.find_nearest(sample, K); has most definitely to be wrong.
There is now function at in object Mat.
Also there is no "evaluate function".
Another thing is where does the prediction Mat belong to?In java you can not just put it in the end of the class.
Thanks=)
The following code is for finding the digits
here's some code to try:
import org.opencv.core.*;
import org.opencv.imgproc.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.ml.*;
import org.opencv.utils.*;
import java.util.*;
class SimpleSample {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) {
// samples/data/digits.png, have a look at it.
Mat digits = Imgcodecs.imread("digits.png", 0);
// setup train/test data:
Mat trainData = new Mat(),
testData = new Mat();
List<Integer> trainLabs = new ArrayList<Integer>(),
testLabs = new ArrayList<Integer>();
// 10 digits a 5 rows:
for (int r=0; r<50; r++) {
// 100 digits per row:
for (int c=0; c<100; c++) {
// crop out 1 digit:
Mat num = digits.submat(new Rect(c*20,r*20,20,20));
// we need float data for knn:
num.convertTo(num, CvType.CV_32F);
// 50/50 train/test split:
if (c % 2 == 0) {
// for opencv ml, each feature has to be a single row:
trainData.push_back(num.reshape(1,1));
// add a label for that feature (the digit number):
trainLabs.add(r/5);
} else {
testData.push_back(num.reshape(1,1));
testLabs.add(r/5);
}
}
}
// make a Mat of the train labels, and train knn:
KNearest knn = KNearest.create();
knn.train(trainData, Ml.ROW_SAMPLE, Converters.vector_int_to_Mat(trainLabs));
// now test predictions:
for (int i=0; i<testData.rows(); i++)
{
Mat one_feature = testData.row(i);
int testLabel = testLabs.get(i);
Mat res = new Mat();
float p = knn.findNearest(one_feature, 1, res);
System.out.println(testLabel + " " + p + " " + res.dump());
}
//// hmm, the 'real world' test case probably looks more like this:
//// make sure, you follow the very same preprocessing steps used in the train phase:
// Mat one_feature = Imgcodecs.imread("one_digit.png", 0);
// Mat feature; one_feature.convertTo(feature, CvTypes.CV_32F);
// Imgproc.resize(feature, feature, Size(20,20));
// int predicted = knn.findNearest(feature.reshape(1,1), 1);
}
}

How to use joptimizer for linear programming

I am working on solving a linear programming problem using joptimizer.
My problem is:
Maximize (x1*f1 + x2*f2 + x3*f3)
such that (x1*v1 + x2*v2 + x3*v3) <= h
I need to find x1, x2 and x3.
I do not know how to create a joptimizer input from the above equation.
Java doc is available here
http://www.joptimizer.com/apidocs/index.html
simple example
minimize 3x+4y such that 2x+3y >= 8, 5x+2y >= 12, x >= 0, y >= 0
My sample code for solving simple linear programming question is below:
package test_joptimizer;
import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
import org.apache.log4j.BasicConfigurator;
/**
* #author K.P.L.Kanchana
*/
public class Main {
public static void main(String[] args) throws Exception {
// Objective function (plane)
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {3.0, 4.0}, 0); //minimize 3x+4y
//inequalities (polyhedral feasible set G.X<H )
ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];
// x >= 0
inequalities[0] = new LinearMultivariateRealFunction(new double[]{-1.0, 0.00}, 0.0); // focus: -x+0 <= 0
// y >= 0
inequalities[1] = new LinearMultivariateRealFunction(new double[]{0.0, -1.00}, 0.0); // focus: -y+0 <= 0
// 2x+3y >= 8
inequalities[2] = new LinearMultivariateRealFunction(new double[]{-2.0, -3.00}, 8.0); // focus: -2x-3y+8 <= 0
// 5x+2y >= 12
inequalities[3] = new LinearMultivariateRealFunction(new double[]{-5.0, -2.00}, 12.0);// focus: -5x-2y+12 <= 0
//optimization problem
OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
//or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory
or.setToleranceFeas(1.E-9);
or.setTolerance(1.E-9);
//optimization
JOptimizer opt = new JOptimizer();
opt.setOptimizationRequest(or);
int returnCode = opt.optimize();
double[] sol = opt.getOptimizationResponse().getSolution();
System.out.println("Length: " + sol.length);
for (int i=0; i<sol.length/2; i++){
System.out.println( "X" + (i+1) + ": " + Math.round(sol[i]) + "\ty" + (i+1) + ": " + Math.round(sol[i+1]) );
}
}
}
Maybe you would like to have a look at the following sample code too.
Don't forget to import the dependecies from http://www.joptimizer.com/downloadWithAdd.html.
You should download and import external three jar files ( /joptimizer-4.0.0.jar, /joptimizer-4.0.0-dependencies.zip, /joptimizer-4.0.0-sources.jar) into your project manually. The .zip file demands unzipping too.
import java.util.Arrays;
import com.joptimizer.optimizers.*;
public class LCLP {
// min (x) for J = C'*X;
// s.t.
// A*X = b;
// X <= 0;
// X = [x1;x2;x3;...xN]
public static void main(String[] args) throws Exception {
// Example from http://www.joptimizer.com/linearProgramming.html
//Objective function
double[] c = new double[] { -1., -1. };
//Inequalities constraints
double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}};
double[] h = new double[] {2., 1./2., 2., 1./2.};
//Bounds on variables
double[] lb = new double[] {0 , 0};
double[] ub = new double[] {10, 10};
//optimization problem
LPOptimizationRequest or = new LPOptimizationRequest();
or.setC(c);
or.setG(G);
or.setH(h);
or.setLb(lb);
or.setUb(ub);
or.setDumpProblem(true);
//optimization
LPPrimalDualMethod opt = new LPPrimalDualMethod();
opt.setLPOptimizationRequest(or);
opt.optimize();
double[] sol = opt.getOptimizationResponse().getSolution();
System.out.println("Solution = " + Arrays.toString(sol));
}
}

Trying to port python code to Java but getting different results

I'm sure I'm making a rookie mistake with java(this is actually my first program). I am trying to port some working python code I made into java(as a learning/testing exercise to learn a bit of the differences) but I'm getting different results between the two.
My program takes a list of data and generates another list based on it(basically sees if a value can be broken down by a sum). Python correctly gives 2,578 results while Java only gives 12. I tried to find the same commands in java and thought I did but can't seem to figure out why the results differ(the difference between the two I have experienced problems with multi threading and syncing of variables, wasn't sure if Java was doing anything behind the scenes so I had a while loop to keep running until the results stabilize, but it didn't help). Any suggestions would be helpful.
Here's the offending code(java at the top, python and pseudo code commented out in the bottom as reference):
for (int c = 0; c <= max_value; c++){
String temp_result = (s - c * data.get(i) + "," + i);
if( results.contains( temp_result ) ){
String result_to_add = (s + "," + i+1);
if( results.contains( result_to_add ) ){
System.out.println("contains result already");
} else {
results.add(result_to_add);
} print len(T)
#Here's the basic pseudo code(I added a few control variables but here's a high level view):
for i = 1 to k
for z = 0 to sum:
for c = 1 to z / x_i:
if T[z - c * x_i][i - 1] is true:
set T[z][i] to true
*/
In java s + "," + i+1 is a String concatenation : "10" + "," + 4 + 1 will return 10,41.
Use String result_to_add = s + "," + (i+1); instead.
I see you've solved it just now, but since I've written it already, here's my version:
This uses the trick of using a Point as a substitute for a 2-element Python list/tuple of int, which (coincidentally) bypasses your String concatenation issue.
public class Sums
{
public static void main(String[] args)
{
List T = new ArrayList();
T.add(new Point(0, 0));
int target_sum = 100;
int[] data = new int[] { 10, -2, 5, 50, 20, 25, 40 };
float max_percent = 1;
int R = (int) (target_sum * max_percent * data.length);
for (int i = 0; i < data.length; i++)
{
for (int s = -R; s < R + 1; s++)
{
int max_value = (int) Math.abs((target_sum * max_percent)
/ data[i]);
for (int c = 0; c < max_value + 1; c++)
{
if (T.contains(new Point(s - c * data[i], i)))
{
Point p = new Point(s, i + 1);
if (!T.contains(p))
{
T.add(p);
}
}
}
}
}
System.out.println(T.size());
}
}

Categories

Resources