Solves a linear system with two unknowns: c1[0]*x+c1[1]*y+c1[2]=0 c2[0]*x+c2[1]*y+c2[2]=0 - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Solves a linear system with two unknowns: c1[0]*x+c1[1]*y+c1[2]=0 c2[0]*x+c2[1]*y+c2[2]=0

Demo Code

/*//from w w w. ja  v  a  2  s.  c om
 * #%L
 * BlaiseMath
 * --
 * Copyright (C) 2009 - 2016 Elisha Peterson
 * --
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        double[] c1 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000,
                37.1234, 67.2344, 68.34534, 69.87700 };
        double[] c2 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000,
                37.1234, 67.2344, 68.34534, 69.87700 };
        System.out.println(java.util.Arrays.toString(solveLinear(c1, c2)));
    }

    /**
     * Solves a linear system with two unknowns: <br>
     * c1[0]*x+c1[1]*y+c1[2]=0 <br>
     * c2[0]*x+c2[1]*y+c2[2]=0
     * @param c1
     * @param c2
     * @return solution {x,y}, or null if there is not one unique solution
     */
    public static double[] solveLinear(double[] c1, double[] c2) {
        double det = c1[0] * c2[1] - c1[1] * c2[0];
        // det = 0, so zero or many solutions
        if (det == 0) {
            return null;
        }
        return new double[] { (c1[1] * c2[2] - c2[1] * c1[2]) / det,
                -(c1[0] * c2[2] - c2[0] * c1[2]) / det };
    }
}

Related Tutorials