Need help with Linear Equations.

Ok, I have been working on a Linear Equation program that will draw a line on my graph. But, I am not sure how to set up the y=mx+b in Java to return the (x1,y1) and (x2, y2) using only the slope and y-intercept.

This is a snip bit of my program. First it checks if the user wants to graph something, then it takes the data from the two fields the user entered, [ This part need help on. Getting it to find (x1,y1) and (x2, y2) ], then it converts the answer to points that will match up with the graph lines, draws the data on the graph etc...

If you are simply drawing a line, you can use a MouseListener to pick up the points where the mouse is clicked, and draw a line between the two points. To get m use 1.0 * (y2 - y1) / (x2 - x1). The reason for the 1.0 is to force an implicit cast to double. I can't remember how you get b; I think it would be y1 - x1 * m.

Campbell Ritchie

Marshal

Posts: 57443

175

posted 10 years ago

Or you can draw a line between the two points (0, (int)-b) and (w, (int)(-w * m - b)), where w is the width of the component.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Campbell Ritchie

Marshal

Posts: 57443

175

posted 10 years ago

Are you sure it is (0, 0.2) Fred?

I would have thought it is (0, 4), only using positive numbers will make the graph display upside down. Agree the next point is (1, 4.2).

You have y = bx + m. You want to put it in a JPanel w pixels wide and h pixels high. You want the "origin" (0, 0) to appear in the centre of the screen. And remember you have to change the sign of the y values because y = 0 is the top of the screen.

Start off with x = 0. The y value is the same as m. Because your y coordinates run downwards, use (w / 2, h / 2 - m). Go to x = 100. You now want to move 100 px to the right, so the first half of the other point is increased by 100, becoming w / 2 + 100. You want to be 100m pixels higher than the origin, so the second part of the point is reduced by 100 * m, becoming h - 2 - m - 100 * m. [You can see the formula can easily be simplified more.]