Pages

Monday, 29 August 2016

Chapter 8 Exercise 30, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

8.30 (Algebra: solve linear equations) Write a method that solves the following
2 * 2 system of linear equations:
a 00 x + a 01 y = b 0
a 10 x + a 11 y = b 1
x =
b 0 a 11 - b 1 a 01
a 00 a 11 - a 01 a 10
y =
b 1 a 00 - b 0 a 10
a 00 a 11 - a 01 a 10
The method header is
public static double[] linearEquation(double[][] a, double[] b)

The method returns null if a 00 a 11 - a 01 a 10 is 0 . Write a test program that
prompts the user to enter a 00 , a 01 , a 10 , a 11 , b 0 , and b 1 , and displays the result. If
a 00 a 11 - a 01 a 10 is 0 , report that “The equation has no solution.” A sample run is
similar to Programming Exercise 3.3.


package Chapter_08;

import java.util.Scanner;

public class Exercise_30 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a, b, c, d, e, f below:");
        double[][] a = new double[2][2];
        double[] b = new double[2];
        for (int i = 0; i < a.length; i++)
            for (int j = 0; j < a[i].length; i++)
                a[i][j] = input.nextDouble();

        double[] point = linearEquation(a, b);
        if (linearEquation(a, b) == null) {
            System.out.println("No solution.");
        } else {
           System.out.println("x = " + point[0] + " and y = " + point[1]);
        }


    }

    public static double[] linearEquation(double[][] a, double[] b) {

        // equation:
        // ab_Minus_bc = a * d - b * c
        double ab_Minus_bc = a[0][0] * a[1][1] - a[0][1] * a[1][0];

        if (ab_Minus_bc == 0.0) return null;

        // equation:
        // x = (e * d - b * f) / ab_Minus_bc;
        // y = (a * f - e * c) / ab_Minus_bc;
        double[] point = new double[2];
        point[0] = (b[0] * a[1][1] - b[1] * a[0][1]) / ab_Minus_bc;
        point[1] = (b[1] * a[0][0] - b[0] * a[1][0]) / ab_Minus_bc;

        return point;
    }

}

No comments:

Post a Comment