d
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
d
j
Last edited by redbull; May 9th, 2015 at 04:35 PM.
I don't think I could offer much help at the moment but first of all, your title kind of turns people off from helping you. We understand that you're confused about your problem but it doesn't make you different from anyone else. Anyways, to begin addressing your problem, you're confused about how to create a java program that will solve a two-variable equation. From a quick glance at your code, I'm not sure if you understand what you programmed.
From what I see, you're printing an initial statement with the two equations but your loops are a bit confusing. Do you know what a for loop or while does?
I suggest reading The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) and the while loop one in the same page.
I think you should take your instructors advice and think about what string methods you've learned that will enable you to do this program.Instructor says that I will need to use string methods to extract the coefficients so that I can solve the equation.
,hkllj
Last edited by redbull; May 9th, 2015 at 04:35 PM.
Well, looking at your current code, I think you might have some issues. Logically, I can understand what you're trying to do. You want a and b to be the variables holding the equation. C through g will hold the coefficients and h through j will multiply them by two. K through l will replace the coefficients, allowing you to cancel out the y variable. Now what I think you would have a problem with is using the a.indexOf(int) method.
I'd like you to try the following and see what happens:
and etc. for the variables that you're using. Are they doing what they want you to? If not, do you understand why they aren't?
lkj
Last edited by redbull; May 9th, 2015 at 04:35 PM.
Well, I tried to compile the code you have now and it won't compile. There quite a bit of errors but I'd like to point out that you won't get the values that you're expecting. If you followed what I suggested, you'd find that your variables will return -1. Also, you declared all your variables as type double. I honestly think you should restart this and go step by step with a pencil and paper. I'd like to help you more but I'm about to go to bed, so I'd have to help you tomorrow. Hopefully someone else will take over and give you some support.
What I'll leave off with is this:
When you declared
a = 5x+3y=9;
b = 2x+6y=5;
This is not a working code. To make it how you want it to be, I'd suggest making a String, so that you'd be able to use String methods, *possibly* the charAt() method *wink* *wink*
Example: String a = "Expression here";
*note* The index starts from left to right, 0 to whatever size it is. Like "5x+3y=9" will have 5 at index 0, 3 at index 3, and 9 at index 6.
I hope that you'll be able to straighten this out and don't worry, coding is not easy and it takes time. It's good to make these mistakes early and to learn from them.
hello, I just bumped to your thread, and did a fast read... I dont know if i could give a help and I'm not sure if this would be a good suggestion. but you could check with converting infix-to-postfix notation, to evaluate any expression easily, Its what im doing right now, and I found that instead of evaluating infix expression directly, its better to convert it to postfix first then later evaluate it...
The ultimate goal is to find numerical values of x and y defined by the set of linear algebraic equations
ax + by = e
cx + dy = f
Where LHS (left-hand side) coefficients a, b, c, d and RHS (right-hand side) variables e, f are, somehow, extracted from user input Strings.
For example
3x+3y=9
Or
1.2x+3.4y=5.6
Now, saying that the strings are "such as "3x+3y=9" and "4x+6y=11"" is not a particularly good specification.
Suppose we know that they are exactly defined by the following, where "(number)" means a decimal integer or floating point number and there are no spaces between the tokens in the string. (The parentheses are not part of the input, they are there to show the nature of the individual tokens.)
(number)(character 'x')(character '+')(number)(character 'y')(character '=')(number)
If this is the input specification, then you can use the String.indexOf() method to find the positions of the 'x', 'y', '+', and '=' characters and then use the String.substring() method to get numerical substrings and then use Double.parseDouble() on each substring to get numerical values of a, b, e from the first user input String and numerical values of c, d, f from the second user input String. Such a method could also handle slight variations such as "4x-6y=11" for this particular input specification.
On the other hand if optional spaces are allowed, then the simplest code for extracting coefficients from "4 x + 6 y = 11" might not work for "4 x - 6 y = 11" (That is to say, you might have to do a little more work to get an extraction algorithm that would work for all such cases with optional spaces in the Strings and with operator that could be either '+' or '-' for a given equation.)
What if someone gave equations in terms of, say, u and v instead of x and y? Are you supposed to handle that also?
My point is: Define input as precisely as is required so that you can create code to get numerical values of a, b, c, d, e, f into your program. If the input specification changes, then you may have to change the extraction algorithm, but the point is, you need to get numerical values of a, b, c, d, e, f into your program
That was the hard part. The rest is easy, but only if we think about what we are doing and, maybe, practice a little before trying to write the code.
So...
Suppose you have, somehow, extracted numerical values of a, b, c, d, e, f from the input Strings. Now what?
Well, it's relatively easy to write Java code to handle numerical operations. Not so easy to manipulate symbolic algebraic expressions mathematically. In other words, for numerical solutions, you deal with numbers, not equations.
A simple system of two linear equations and two unknowns is easy to solve "by hand," right? You already know how, right? So, how about practicing with the example you were given?
3x+3y=9
4x+6y=11
Wait a minute while I get a pencil and some paper to whip out a solution. Since this will be my test case for the program, we will need to know the solution if we are going to write a program to solve the system anyhow, right? I mean, I always (always always) work out a test strategy before writing code. Really. Always. For numerical problems that means that I will throw the program a problem for which I already know the answer.
So while I am getting my stuff together, why don't you solve it?
I'll be right back...
Tick
Tick
Tick
OK! Well, I got x = 3.5, y = -0.5. How about you?
My ninth grade algebra teacher, Mrs. Watson, taught us always to check our work. (Thanks, Mrs. Watson, wherever you are. You taught the importance of logical thinking. You taught us not to panic when we are confronted with a problem for which we don't see an immediate solution. You taught us not to get mad if a teacher gave us a problem on a test or homework assignment that wasn't exactly, word for word, like one in the book. I remember every single thing you taught us. Really.)
So...
When I checked the residuals by plugging these solution values into the original equations, I got
3x+3y-9 = 10.5-1.5-9 = 0
4x+6y-11 = 14-3-11 = 0
Taa-daa!
Now, how did I solve the equations?
ax+by=e
cx+dy=f
I'll show it symbolically, but, remember, in my computer program, I'll use the results that I derive here to just plug in numerical values for a, b, c, d, e, f. In other words, I will derive equations 'by hand,' and write code that simply evaluates the expressions that I come up with.
Symbolically: "solve" the first equation for x in terms of y:
x = (e-by)/a
Symbolically, plug this "value" into the second equation:
c(e-by)/a + dy = f
Simple algebra (simple for us brilliant Humans; not so simple for not-so-brilliant computers) lets me get an expression for y in terms if the input numerical values.
Namely, y = (af-ce)/(ad-bc)
Note that this works if (and only if) the expression ad-bc is not equal to zero. If that expression is zero, the equations are not linearly independent. In that case there are either
1. No solutions (equations are inconsistent)
or
2. An infinite number of solutions (they are consistent but one equation is simply a multiple of the other).
Those cases aren't as interesting (numerically) as the case where that expression is not zero, since a non-zero value of (ad-bc) leads to unique values of x and y. That's what the program will find.
Anyhow, assuming that expression has a non-zero value...
I can "plug" that symbolic expression for y back into the first equation and get an expression for x in terms of a, b, c, d, e, f. (I'll leave that up to you).
So here's the program flow:
- Get numerical values of a, b, c, d, e, and f from the user's input Strings.
- Calculate the value of (a*d - b*c). If the result is zero, the equations are not linearly independent. No solution will be attempted.
- If the value of (a*d - b*c) is not equal to zero, calculate numerical values of x and y by plugging values of a, b, c, d, e, f into the equations previously derived.
- Taa-daa! Print the solutions
A general-purpose method for solving systems of linear algebraic equations can be found in this Reference: Cramer's Rule - Wikipedia.
In fact, the expression for y that I give above is the same as shown in that article for the two-equation example. (It had better be the same, right? I mean the solutions are unique under the conditions that I spelled out above.)
Now, if the input variables are all integers and you want rational number outputs (instead of floating point numbers), just calculate the two numerators and the denominator. Then print each "numerator / denominator." (Don't forget to reduce the rational number fraction to lowest terms by dividing by Greatest Common Divisor of numerator and denominator for each output.) So my test case would have solution x = 7/2 and y = -1/2.
A final note:
Cramer's rule might be perfectly appropriate for small systems (like our system of two equations and two unknowns), but the number of calculations grows as N factorial (where N is the number of equations). Numerical analyists never (really, never) use Cramer's rule for systems of, say, ten equations and ten unknowns. (Well, they might use such a system in a pedagogical setting to illustrate that it's really Not The Thing To Do, but they wouldn't actually use it to solve a "real" problem.) Other, more efficient methods are well known and characterized.
Cheers!
Z
Last edited by Zaphod_b; September 25th, 2012 at 03:13 PM.
ChicoTheMan94 (September 25th, 2012)
khkj
Last edited by redbull; May 9th, 2015 at 04:36 PM.
kjhjhj
Last edited by redbull; May 9th, 2015 at 04:36 PM.
I didn't show how to extract coefficients from strings. but I gave some hints, as have other helpers.
If you had given the exact input specification at first, my previous post could have been a little less wordy. (That would have been a blessing, right?)
Anyhow...
Here's the assignment in a nutshell:
You are going to solve a system of two equations and two unknowns.
The user enters two strings. Each string represents one of the equations. The form of the strings is in your assignment.
Get it? The program solves one problem. The user gives the equation coefficients and other values in a particular form. It takes two strings to specify values for the two equations. The program solves this system for for x and y. That's one solution. A value of x and a value of y.
To solve the equations, you must first extract the four left-hand side coefficients and the two right-hand side values from the two user input strings.
I called the variables a, b, c, d, e, f. (Which conveniently corresponds to the variables in the Wikipedia article that I linked to.)
Now, once you get the six numeric values for those variables, you solve the system for x and y. I indicated one way. The complete Cramer's rule formulas for two equations and two unknowns are in the Wikipedia reference that I gave you. If you don't want to use those expressions, do it any way that you want to. Well, do it any way that is mathematically correct (and, in particular that gives the correct answers that we so carefully worked out ahead of time).
Bottom line: There are lots of ways to write a program that solves two equations and two unknowns, but if your program reads input values correctly and gives incorrect answers, then it the algorithm is wrong. That's why I always (yes always) start with a problem for which I know the answer. (But I said that already.) Period. Full stop.
Some variation of Gauss reduction and back substitution using matrix variables is the most common way that "real" numerical analysts do it, especially for systems with more than a couple of equations. You can look them up.
Anyhow...
Here is my vision of a run. User input is black, program output is blue.
Enter the first equation in the form ax+by=e: 3x+3y=9
Enter the second equation in the form cx+dy=f: 4x+6y=11
Here are the equations to be solved:
3 * x + 3 * y = 9
4 * x + 6 * y = 11
Here is the solution:
x = 3.500000, y = -0.500000
The program skeleton looks like this:
public class Z { public static void main(String [] args) { int a, b, c, d, e, f; double x, y; Scanner keyboard = new Scanner(System.in); System.out.printf("Enter the first equation in the form ax+by=e: "); String first = keyboard.nextLine(); System.out.printf("Enter the second equation in the form cx+dy=f: "); String first = keyboard.nextLine(); // // Your code goes here: // Extract values of a, b, e from the first String // Extract values of c, d, f from the second String // // // Print out the equations so that we know the values // were read in correctly. // System.out.println("Here are the equations to be solved:"); System.out.printf("%2d * x + %2d * y = %2d\n", a, b, e); System.out.printf("%2d * x + %2d * y = %2d\n", c, d, f); // // Your code goes here: // Calculate x and y from the values of a, b, c, d, e, f // // // // Now print out the answer. System.out.println("Here is the solution:"); System.out.printf("x = %f, y = %f\n", x, y); } }
While debugging, you can just set the values of the Strings internally instead of reading from user input, so that you won't have to type the blasted stuff each and every stinking time that you run it while correcting bugs.
public class Z { public static void main(String [] args) { int a, b, c, d, e, f; double x, y; // Comment out user input while debugging //Scanner keyboard = new Scanner(System.in); //System.out.printf("Enter the first equation in the form ax+by=e: "); //String first = keyboard.nextLine(); //System.out.printf("Enter the second equation in the form cx+dy=f: "); //String first = keyboard.nextLine(); // While debugging, just use fixed Strings instead of user input // String first = "3x+3y=9"; String second = "4x+6y=11"; // // Your code goes here: // Extract values of a, b, e from the first String // Extract values of c, d, f from the second String // // . . .
Cheers!
Z
ChicoTheMan94 (September 26th, 2012)
jgkjhjhj
Last edited by redbull; May 9th, 2015 at 04:36 PM.
hkjhhhjkh
Last edited by redbull; May 9th, 2015 at 04:36 PM.
I thought you had been given some hints. Oh, well...
- Make the first substring dependent on the position of the character 'x' in each equation's String.
- Make the second substring dependent on the position of the character '+' and the position of the character 'y' in each equation's String.
- Make the third substring dependent on the position of the character '=' in each equation's String.
Here's a start:
How can you use indx1 as an argument to s1.substring() to get the String for the first coefficient of the first equation?
How can you use indx2 as an argument to s2.substring() to get the String for the first coefficient of the second equation?
Next step:
Find the indexOf('+') and indexOf('y') for each equation. Use those values, somehow, to get the correct substrings for the second coefficients.
Next step:
Find the indexOf('=') for each equation. Use those values, somehow, to get the correct substrings for the right-hand side values.
Your program does not work for me even within the limitation of one digit per constant. I mean, it does not give correct answers for anything I tried. What did you test it with?
Try it with, say "1x+2y=5 2x+3y=8"
What does the program tell you is the answer? What is the actual answer? (Solve by hand. Compare with program output. In each case, check the answer by calculating residuals as I did in my previous post.)
Solve a problem manually with whatever method you think appropriate for the program. Then, go the program, step by step and print out the intermediate values being calculated. Compare each and every one with your manual calculations and make sure they agree.
That way, if your manual calculations are correct, so will be the program's.
Bada-bing, bada-boom!
Cheers!
Z
Last edited by Zaphod_b; September 25th, 2012 at 10:55 PM.
ChicoTheMan94 (September 26th, 2012)
jhgkgkjh
Last edited by redbull; May 9th, 2015 at 04:37 PM.
kjhkjhkjh
Last edited by redbull; May 9th, 2015 at 04:37 PM.
Cheat Sheet for printf format specifier
Use whatever the heck you want.
public class Z { public static void main(String [] args) { int x = 12; int y = 12345; System.out.printf("First example: x = %d, y = %d\n", x, y); // Same as System.out.println("Second example: x = " + x + ", y = " + y); System.out.println(); // Suppose you want them to line up the numbers on successive rows. // Each can be 1-5 digits, so make the field width = 5; System.out.printf("x = %5d\n", x); System.out.printf("y = %5d\n", y); // Try lining them up using fixed field widths with print() // and/or println(). // // You have to use a separate formatter string, which (to me) is // more trouble than using printf. // Chacun à son goût } }
Output:
First example: x = 12, y = 12345 Second example: x = 12, y = 12345 x = 12 y = 12345
Cheers!
Z
Last edited by Zaphod_b; September 26th, 2012 at 12:04 AM.
I use nextLine() as a matter of habit since it empties out the stream input buffer so that I can do another nextLine() later to get another user input string and not be faced with a leftover terminating character or other stuff from previous input. I mean, I usually develop programs incrementally, and even though I'm not doing any more input at this stage, I might add some later.
It doesn't cost anything extra to leave things in a clean state, right? So why not do it?
Cheers!
Z
Last edited by Zaphod_b; September 26th, 2012 at 12:17 AM.