Skip to content

Commit 49ae4f7

Browse files
authored
Create Rainbow Program
1 parent b0225b7 commit 49ae4f7

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Rainbow Program

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.awt.Color;
2+
3+
public class Rainbow {
4+
5+
public static void main(String[] args) {
6+
7+
int N = Integer.parseInt(args[0]);
8+
int SIZE = 1000;
9+
StdDraw.setCanvasSize(SIZE, SIZE/2);
10+
StdDraw.setXscale(0, SIZE);
11+
StdDraw.setYscale(0, SIZE/2.0);
12+
StdDraw.enableDoubleBuffering();
13+
14+
// sky blue background
15+
Color skyblue = new Color(48, 144, 199);
16+
StdDraw.clear(skyblue);
17+
18+
// simulate N incident light rays
19+
for (int i = 0; i < N; i++) {
20+
21+
// generate random (x, y) uniformly in unit circle centered at (0, 0)
22+
double r = Math.random(); // impact parameter
23+
double theta = Math.random() * 2 * Math.PI; // between 0 and 2*pi
24+
double x = Math.sqrt(r) * Math.sin(theta);
25+
double y = Math.sqrt(r) * Math.cos(theta);
26+
27+
float c = (float) Math.random(); // random hue of rainbow
28+
double n = 1.33 + 0.06 * c; // refraction index
29+
30+
double thetaI = Math.asin(r); // angle of incidence
31+
double thetaR = Math.asin(r / n); // angle of refraction
32+
double thetaP = 4*thetaR - 2*thetaI; // primary rainbow angle
33+
double thetaS = 6*thetaR - 2*thetaI - Math.PI; // secondary rainbow angle
34+
35+
// intensities of principle and secondary
36+
double p = Math.pow(Math.sin(thetaI - thetaR) / Math.sin(thetaI + thetaR), 2);
37+
double s = Math.pow(Math.tan(thetaI - thetaR) / Math.tan(thetaI + thetaR), 2);
38+
double intensityP = 0.5 * ( s*(1-s)*(1-s) + p*(1-p)*(1-p));
39+
double intensityS = 0.5 * (s*s*(1-s)*(1-s) + p*p*(1-p)*(1-p));
40+
41+
// plot primary rainbow
42+
float saturation = (float) Math.min(intensityP / 0.04, 1.0);
43+
StdDraw.setPenColor(Color.getHSBColor(c, saturation, 1.0f));
44+
double xp = (SIZE/2.0 * thetaP * 3 / Math.PI * x / r) + SIZE / 2.0;
45+
double yp = (SIZE/2.0 * thetaP * 3 / Math.PI * Math.abs(y) / r);
46+
StdDraw.point(xp, yp);
47+
48+
// plot secondary rainbow
49+
saturation = (float) Math.min(intensityS / 0.02, 1.0);
50+
StdDraw.setPenColor(Color.getHSBColor(c, saturation, 1.0f));
51+
double xs = ( SIZE/2.0 * thetaS * 3 / Math.PI * x / r) + SIZE / 2.0;
52+
double ys = (-SIZE/2.0 * thetaS * 3 / Math.PI * Math.abs(y) / r);
53+
StdDraw.point(xs, ys);
54+
55+
// display every 1000 iterates
56+
if (i % 1000 == 0) {
57+
StdDraw.show();
58+
StdDraw.pause(10);
59+
}
60+
}
61+
62+
StdDraw.show();
63+
}
64+
65+
}

0 commit comments

Comments
 (0)