1、使用 jfreechart 显示函数曲线
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
示例代码:
@Test
public void lineTest() throws Throwable{
StandardChartTheme standardChartTheme = new StandardChartTheme("CN");// 创建主题样式
standardChartTheme.setExtraLargeFont(new Font("宋书", Font.BOLD, 20));// 设置标题字体
standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));// 设置图例的字体
standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));// 设置轴向的字体
ChartFactory.setChartTheme(standardChartTheme);// 应用主题样式
CategoryDataset mDataset = GetDataset();
JFreeChart mChart = ChartFactory.createLineChart(
"",//图名字
"x",//横坐标
"f(x)",//纵坐标
mDataset,//数据集
PlotOrientation.VERTICAL,
false, // 显示图例
false, // 采用标准生成器
false);// 是否生成超链接
CategoryPlot mPlot = (CategoryPlot)mChart.getPlot();
mPlot.setBackgroundPaint(Color.WHITE);
mPlot.setRangeGridlinePaint(Color.BLUE);//背景底部横虚线
mPlot.setOutlinePaint(Color.BLUE); //边界线
//setDomainAxis(mPlot.getDomainAxis(), categories);
ChartFrame mChartFrame = new ChartFrame("折线图", mChart);
mChartFrame.setPreferredSize(new Dimension(1200, 400));
mChartFrame.pack();
mChartFrame.setVisible(true);
Thread.sleep(1000000);
}
// 控制横坐标显示间隔
private void setDomainAxis(CategoryAxis domainAxis, List<String> categories){
domainAxis.setTickLabelFont(new Font("Times New Roman", Font.ITALIC, 14));
domainAxis.setLabelFont(new Font("Times New Roman", Font.ITALIC, 14));
domainAxis.setTickMarksVisible(true); //用于显示X轴标尺
domainAxis.setTickLabelsVisible(true); //用于显示X轴标尺值
for(int i = 0; i< categories.size(); i++){
String s = categories.get(i);
if(i%5 != 0){
domainAxis.setTickLabelPaint(s, Color.white);
} else {
domainAxis.setTickLabelPaint(s, Color.black);
}
}
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); //设置X轴45度
}
public static CategoryDataset GetDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = -10; i < 10; i++) {
dataset.addValue(fun(i), "X", String.valueOf(i));
}
return dataset;
}
private static double fun(double x){
return x*x+2*x+1;
}
2、常见函数
2.1 一元二次函数
y = x 2 + 2 x + 1 y=x^2+2x+1 y=x2+2x+1
private static double fun(double x){
return x*x+2*x+1;
}

2.2 倒数函数
y = 1 x y=\frac{1}{x} y=x1
代码
public static CategoryDataset GetDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (double i = -1; i < 0; i+=0.01) {
dataset.addValue(fun(i), "Y", String.valueOf(i));
}
for (double i = 0.01; i < 1; i+=0.01) {
dataset.addValue(fun(i), "X", String.valueOf(i));
}
return dataset;
}
private static double fun(double x){
if (x == 0) {
return 0;
}
return 1/x;
}

2.3 指数函数
y = ( 2 3 ) x y=(\frac{2}{3})^x y=(32)x

2.4 双曲正切 tanh
y = e x − e − x e x + e − x y=\frac{e^x-e^{-x}}{e^x+e^{-x}} y=ex+e−xex−e−x
代码:
private static double tanh(double x) {
return (Math.exp(x) - Math.exp(-x))/(Math.exp(x) + Math.exp(-x));
}

887

被折叠的 条评论
为什么被折叠?



