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.
Can anyone tell me how to set up the linear equation in java.
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.
Joined: Oct 13, 2005
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.
The reason for the - is that the y coordinates go from top to bottom.
Change y to b in two places and add an (int) cast[/edit] [ May 25, 2007: Message edited by: Campbell Ritchie ]
You have the slope and the intercept. by definition that means that one point is (0,b).
If all you need is another point, just pick any value for x you want - say, 1. then, stick it into the slope/intercept formula, and calculate y. you now have two points.
example: Slope = 0.2 Intercept = 4
point 1 = ( 0 , 4 )
to find point 2, pick a value for x2, say 1.
i know that y2 = (m)(x2) + b. so, y2 = (0.2) (1) + 4 = 0.2 + 4 = 4.2
point 2 = ( 1 , 4.2 ) [ May 25, 2007: Message edited by: Fred Rosenberger ]
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Oct 13, 2005
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 JPanelw 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.]