# [OT] How to plot a Math.sin() equation

Ranch Hand
Posts: 57
Hi everyone,

Off topic question - I want to plot a Math.sin() equation
and I got stuck on translation values to real pixel coordinates.
How to scale these values ? Assuming that I have a JPanel
with 300 width and 150 height dimension. What do I need to do ?

Thanks,

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
Well, the range forthe output values of sin() is -1 to 1. The range of y values in your panel is 0 to 149.

You can simply translate one to the other with a simple addition and multiplication.

1) -1...1 -> 0...2: add 1
2) 0...2 -> 0...149: multiply by 149/2 = 74.5

Ranch Hand
Posts: 57
Hi Jesper,

Thanks a lot for the tip !

Could you please take a look at this code snippet:

It is supposed to draw a sin(x) for x=-2*pi to x=+2*pi and indeed it does.
The only problem is that I need to resize the window (which is now 300 width
and 200 height) to see the whole graph. I know that some part of the
window is taken by the title bar, so I would have to take it into account
in my calculations. However I wonder why I lack about 10 pixels to see
the graph in full horizontally ? To avoid it, I need to create a window
of size: JFrame(310 instead of 300 ???, 230 instead of 200 because of the title bar).

Thanks,

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
I made the following small program to display your sinusoid and it displays fine, I don't need to resize the window to see it:

Ulf Dittmer
Rancher
Posts: 42968
73
I think this code makes a nice example for plotting a function, so I added it as sample code to the FAQ: http://faq.javaranch.com/view?PlotSineCurve. In addition, the plot adapts to the frame size, and optionally a line is drawn connecting the dots.
[ July 09, 2007: Message edited by: Ulf Dittmer ]

Ranch Hand
Posts: 57
Thanks a lot guys !

PS. Ulf - I think you need to change the comment in your class
from "0 to 2*PI" to "-2*PI to 2*PI"

Cheers,