Reputation: 57
Hello I am trying to create a java program that allows you to graph an equation and its been working well so far until I wanted it to graph cosine and sine functions. I am confused on how I can do this when sine and cosine return doubles but drawLine only takes in integers. I am new to java so this may be easy but if you could help I would appreciate it.
Here is my code:
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.lang.Math;
import java.awt.geom.*;
class PlotGraph extends JFrame{
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g.drawLine(50, 300, 550, 300); //x axis
g.drawLine(300, 550, 300, 50); //y axis
//Orignin x = 300 y = 300
double xmin, xmax;
double y;
xmin =(0);
xmax = 100;
double x = xmin;
double form = Math.cos(x);
double last_y = 300-(form);
for (x = xmin+1; x<=xmax; x++){
double newForm = Math.cos(x);
y = 300-(newForm);
g2.draw(new Line2D.Double(x-1+(300), last_y, x+300, y));
last_y = y;
}
}
public static void main(String [] args) {
PlotGraph graph = new PlotGraph();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(600, 600);
graph.setVisible(true);
graph.setTitle("PlotGraph");
}
}
Upvotes: 0
Views: 4798
Reputation: 2242
Try casting the double to an int.
int y = 300 - (int) (Math.cos(x) * scaleFactor);
And as Aiias said: cos will only return values between -1 and 1. So make sure you multiply it by a constant factor or you will lose the value after casting.
Upvotes: 0
Reputation: 425198
Since Math.cos() returns a value between -1 and 1, casting to int will result in only 3 values -1, 0 and 1, and will almost always be 0.
What you want to do is multiply the double by a large constant to create a range of integers:
y = 300-(int)(300d * newForm);
Note the "d" after the 300: that makes the 300 a double, making the result if the multiplication also double, this keeping fine granularity.
Upvotes: 2
Reputation: 285405
Use Line2D.Double objects, a Graphics2D Graphics object and have the Graphics2D object draw the shape with its draw(...)
method.
Upvotes: 1
Reputation: 8463
After properly scaling, you might try either of:
typecast the double
to an int
: int i = (int)d;
rounding, which returns long
which must by typecast to int
: int i = (int)Math.round(d);
Upvotes: 0