logo
  • Home
  • Rank
  • Tests
  • About
  • Training
  • Programming
  • CS
  • IT
  • IS
  • ECE
  • EEE
  • EE
  • Civil
  • Mechanical
  • Chemical
  • Metallurgy
  • Instrumentation
  • Aeronautical
  • Aerospace
  • Biotechnology
  • Agriculture
  • MCA
  • BCA
  • Internship
  • Contact

Questions & Answers

C Interview Questions
C++ Questions
Linux MCQs
C# Quiz
Java MCQs
JavaScript MCQs
SAN Questions
PHP Questions
Python Quiz

Computer Science Questions

Operating System Quiz
Computer Architecture MCQs
Software Architecture MCQs
Software Engineering MCQs
Artificial Intelligence MCQs
LISP Programming MCQs
Database Management MCQs
Computer Network MCQs
Microprocessor MCQs

C Programming Examples

Simple C Programs
C - Arrays
C - Matrix
C - Strings
C - Bitwise Operations
C - Linked Lists
C - Stacks & Queues
C - Searching & Sorting
C - Trees
C - Strings
C - File Handling
C - Mathematical Functions
C - Puzzles & Games
C Programs - Recursion
C Programs - No Recursion

Java Algorithms

Java - Numerical Problems
Java - Combinatorial Problems
Java - Graph Problems
Java - Hard Graph Problems
Java - Computation Geometry
Java - Sets & Strings
Java - Data-Structures
Java - Collection API Problems

C++ Algorithms

C++ - Numerical Problems
C++ - Combinatorial Problems
C++ - Graph Problems
C++ - Hard Graph Problems
C++ - Computation Geometry
C++ - Sets & Strings
C++ - Data-Structures
C++ - STL Library

C Algorithms

C - Numerical Problems
C - Combinatorial Problems
C - Graph Problems
C - Hard Graph Problems
C - Computation Geometry
C - Sets & Strings
C - Data-Structures

« Prev Page
Next Page »

Java Program to Solve any Linear Equations

Posted on June 1, 2014 by dharmendra
This is java program to solve the system of linear equations. This can be done by first representing equations(vectors) to matrix form, then finding the inverse of the matrix formed by the coefficients of variable and multiplying it with constants.

Here is the source code of the Java Program to Solve any Linear Equation in One Variable. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a sample program to solve the linear equations.
  2. import java.util.Scanner;
  3.  
  4. public class Solve_Linear_Equation 
  5. {
  6.     public static void main(String args[])
  7.     {
  8.         char []var = {'x', 'y', 'z', 'w'};
  9.         System.out.println("Enter the number of variables in the equations: ");
  10.         Scanner input = new Scanner(System.in);
  11.         int n = input.nextInt();
  12.         System.out.println("Enter the coefficients of each variable for each equations");
  13.         System.out.println("ax + by + cz + ... = d");
  14.         double [][]mat = new double[n][n];
  15.         double [][]constants = new double[n][1];
  16.         //input
  17.         for(int i=0; i<n; i++)
  18.         {
  19.             for(int j=0; j<n; j++)
  20.             {
  21.                 mat[i][j] = input.nextDouble();
  22.             }
  23.             constants[i][0] = input.nextDouble();
  24.         }
  25.         //Matrix representation
  26.         for(int i=0; i<n; i++)
  27.         {
  28.             for(int j=0; j<n; j++)
  29.             {
  30.                 System.out.print(" "+mat[i][j]);
  31.             }
  32.             System.out.print("  "+ var[i]);
  33.             System.out.print("  =  "+ constants[i][0]);
  34.             System.out.println();
  35.         }
  36.         //inverse of matrix mat[][]
  37.         double inverted_mat[][] = invert(mat);
  38.         System.out.println("The inverse is: ");
  39.         for (int i=0; i<n; ++i) 
  40.         {
  41.             for (int j=0; j<n; ++j)
  42.             {
  43.                 System.out.print(inverted_mat[i][j]+"  ");
  44.             }
  45.             System.out.println();
  46.         }
  47.         //Multiplication of mat inverse and constants
  48.         double result[][] = new double[n][1];
  49.         for (int i = 0; i < n; i++) 
  50.         {
  51.             for (int j = 0; j < 1; j++) 
  52.             {
  53.                 for (int k = 0; k < n; k++)
  54.                 {	 
  55.                     result[i][j] = result[i][j] + inverted_mat[i][k] * constants[k][j];
  56.                 }
  57.             }
  58.         }
  59.         System.out.println("The product is:");
  60.         for(int i=0; i<n; i++)
  61.         {
  62.             System.out.println(result[i][0] + " ");
  63.         }
  64.         input.close();
  65.  
  66.     }
  67.  
  68.     public static double[][] invert(double a[][]) 
  69.     {
  70.         int n = a.length;
  71.         double x[][] = new double[n][n];
  72.         double b[][] = new double[n][n];
  73.         int index[] = new int[n];
  74.         for (int i=0; i<n; ++i) 
  75.             b[i][i] = 1;
  76.  
  77.  // Transform the matrix into an upper triangle
  78.         gaussian(a, index);
  79.  
  80.  // Update the matrix b[i][j] with the ratios stored
  81.         for (int i=0; i<n-1; ++i)
  82.             for (int j=i+1; j<n; ++j)
  83.                 for (int k=0; k<n; ++k)
  84.                     b[index[j]][k]
  85.                     	    -= a[index[j]][i]*b[index[i]][k];
  86.  
  87.  // Perform backward substitutions
  88.         for (int i=0; i<n; ++i) 
  89.         {
  90.             x[n-1][i] = b[index[n-1]][i]/a[index[n-1]][n-1];
  91.             for (int j=n-2; j>=0; --j) 
  92.             {
  93.                 x[j][i] = b[index[j]][i];
  94.                 for (int k=j+1; k<n; ++k) 
  95.                 {
  96.                     x[j][i] -= a[index[j]][k]*x[k][i];
  97.                 }
  98.                 x[j][i] /= a[index[j]][j];
  99.             }
  100.         }
  101.         return x;
  102.     }
  103.  
  104. // Method to carry out the partial-pivoting Gaussian
  105. // elimination.  Here index[] stores pivoting order.
  106.  
  107.     public static void gaussian(double a[][], int index[]) 
  108.     {
  109.         int n = index.length;
  110.         double c[] = new double[n];
  111.  
  112.  // Initialize the index
  113.         for (int i=0; i<n; ++i) 
  114.             index[i] = i;
  115.  
  116.  // Find the rescaling factors, one from each row
  117.         for (int i=0; i<n; ++i) 
  118.         {
  119.             double c1 = 0;
  120.             for (int j=0; j<n; ++j) 
  121.             {
  122.                 double c0 = Math.abs(a[i][j]);
  123.                 if (c0 > c1) c1 = c0;
  124.             }
  125.             c[i] = c1;
  126.         }
  127.  
  128.  // Search the pivoting element from each column
  129.         int k = 0;
  130.         for (int j=0; j<n-1; ++j) 
  131.         {
  132.             double pi1 = 0;
  133.             for (int i=j; i<n; ++i) 
  134.             {
  135.                 double pi0 = Math.abs(a[index[i]][j]);
  136.                 pi0 /= c[index[i]];
  137.                 if (pi0 > pi1) 
  138.                 {
  139.                     pi1 = pi0;
  140.                     k = i;
  141.                 }
  142.             }
  143.  
  144.    // Interchange rows according to the pivoting order
  145.             int itmp = index[j];
  146.             index[j] = index[k];
  147.             index[k] = itmp;
  148.             for (int i=j+1; i<n; ++i) 	
  149.             {
  150.                 double pj = a[index[i]][j]/a[index[j]][j];
  151.  
  152.  // Record pivoting ratios below the diagonal
  153.                 a[index[i]][j] = pj;
  154.  
  155.  // Modify other elements accordingly
  156.                 for (int l=j+1; l<n; ++l)
  157.                     a[index[i]][l] -= pj*a[index[j]][l];
  158.             }
  159.         }
  160.     }
  161. }

Output:

advertisement
$ javac Solve_Linear_Equation.java
$ java Solve_Linear_Equation
Enter the number of variables in the equations: 
2
Enter the coefficients of each variable for each equations
ax + by + cz + ... = d
1 2 3
3 2 1
 
 1.0 2.0  x  =  3.0
 3.0 2.0  y  =  1.0
 
 The inverse is: 
-0.49999999999999994  0.5  
 0.7499999999999999  -0.24999999999999997  
 
 The product is:
-0.9999999999999998 
 1.9999999999999996

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.

« Prev Page - Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
» Next Page - Java Program to Solve the 0-1 Knapsack Problem

« Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Java Program to Solve the 0-1 Knapsack Problem »

Deep Dive @ Sanfoundry:

  1. C# Programming Examples on Matrix
  2. Java Programming Examples on Collection API
  3. Java Programming Examples on Combinatorial Problems & Algorithms
  4. Java Programming Examples on Computational Geometry Problems & Algorithms
  5. C Programming Examples on Numerical Problems & Algorithms
  6. C++ Programming Examples on Numerical Problems & Algorithms
  7. Java Programming Examples on Hard Graph Problems & Algorithms
  8. Java Programming Examples on Graph Problems & Algorithms
  9. Java Programming Examples on Data-Structures
  10. Java Programming Examples on Numerical Problems & Algorithms
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer and SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage & Cluster Administration, Advanced C Programming, SAN Storage Technologies, SCSI Internals and Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him below:
LinkedIn | Facebook | Twitter | Google+

Best Careers

Developer Tracks
SAN Developer
Linux Kernel Developer
Linux Driver Developer
Linux Network Developer

Live Training Photos
Mentoring
Software Productivity
GDB Assignment
Sanfoundry is No. 1 choice for Deep Hands-ON Trainings in SAN, Linux & C, Kernel Programming. Our Founder has trained employees of almost all Top Companies in India such as VMware, Citrix, Oracle, Motorola, Ericsson, Aricent, HP, Intuit, Microsoft, Cisco, SAP Labs, Siemens, Symantec, Redhat, Chelsio, Cavium, ST-Micro, Samsung, LG-Soft, Wipro, TCS, HCL, IBM, Accenture, HSBC, Mphasis, Tata-Elxsi, Tata VSNL, Mindtree, Cognizant and Startups.

Best Trainings

SAN I - Technology
SAN II - Admin
Linux Fundamentals
Advanced C Training
Linux-C Debugging
System Programming
Network Programming
Linux Threads
Kernel Programming
Kernel Debugging
Linux Device Drivers

Best Reference Books

Computer Science Books
Algorithm & Programming Books
Electronics Engineering Books
Electrical Engineering Books
Chemical Engineering Books
Civil Engineering Books
Mechanical Engineering Books
Industrial Engineering Books
Instrumentation Engg Books
Metallurgical Engineering Books
All Stream Best Books

Questions and Answers

1000 C Questions & Answers
1000 C++ Questions & Answers
1000 C# Questions & Answers
1000 Java Questions & Answers
1000 Linux Questions & Answers
1000 Python Questions
1000 PHP Questions & Answers
1000 Hadoop Questions
Cloud Computing Questions
Computer Science Questions
All Stream Questions & Answers

India Internships

Computer Science Internships
Instrumentation Internships
Electronics Internships
Electrical Internships
Mechanical Internships
Industrial Internships
Systems Internships
Chemical Internships
Civil Internships
IT Internships
All Stream Internships

About Sanfoundry

About Us
Copyright
Terms
Privacy Policy
Jobs
Bangalore Training
Online Training
Developers Track
Mentoring Sessions
Contact Us
Sitemap
© 2011 Sanfoundry. All Rights Reserved.