5.4 KiB
5.4 KiB
In [ ]:
%classpath add /opt/tljh/user/share/java/algs4.jar
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdAudio;
StdOut.println("algs4 加载成功!");In [ ]:
// 离屏绘图:sin 曲线
int n = 100;
StdDraw.setCanvasSize(600, 400);
StdDraw.setXscale(0, n);
StdDraw.setYscale(-1.5, 1.5);
StdDraw.setPenColor(StdDraw.BLUE);
for (int i = 0; i < n; i++) {
double x0 = i, y0 = Math.sin(i * 0.1);
double x1 = i + 1, y1 = Math.sin((i + 1) * 0.1);
StdDraw.line(x0, y0, x1, y1);
}
StdDraw.setPenColor(StdDraw.RED);
StdDraw.text(n / 2.0, 1.2, "y = sin(x)");
StdDraw.save("sin_plot.png"); // 保存到当前目录
StdOut.println("已保存 sin_plot.png");In [ ]:
// 用 StdAudio 合成 "小星星" 的前几个音符 (C D E C)
int sampleRate = 44100;
double duration = 0.5; // 每个音 0.5 秒
int n = (int)(sampleRate * duration);
// 频率映射: C4=261.63, D4=293.66, E4=329.63, G4=392.0
double[] notes = {261.63, 293.66, 329.63, 261.63};
double[] all = new double[notes.length * n];
int idx = 0;
for (double freq : notes) {
for (int i = 0; i < n; i++) {
double t = (double)i / sampleRate;
// 正弦波 + 衰减包络(模拟八音盒)
all[idx++] = Math.sin(2 * Math.PI * freq * t) * Math.exp(-4 * t);
}
}
StdAudio.save("twinkle.wav", all); // 保存合成音频
StdOut.println("已合成并保存 twinkle.wav (" + all.length + " samples)");In [ ]:
%maven org.jfree:jfreechart:1.5.4
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import java.awt.image.BufferedImage;
DefaultCategoryDataset ds = new DefaultCategoryDataset();
ds.addValue(95, "CSA", "Tina");
ds.addValue(88, "CSA", "Kevin");
ds.addValue(92, "CSA", "Gerben");
JFreeChart c = ChartFactory.createBarChart(
"AP CSA 成绩", "学生", "分数", ds,
PlotOrientation.VERTICAL, true, true, false);
BufferedImage img = c.createBufferedImage(500, 350);
img // 直接在 notebook 显示 PNG