gpt4 book ai didi

java - JFreeChart 绘制自然对数和 e

转载 作者:行者123 更新时间:2023-11-29 04:56:08 25 4
gpt4 key购买 nike

我正在使用 JFreeChart 绘制一些方程式,例如:x - x^2我正在使用这段代码:(根据提供的示例稍作修改)

double[] a = {0.0, 1.0, -1.0}; // By the model: y = a0 + a1 * x + a2 * x^2 + ... + an * x^n
Function2D p = new PolynomialFunction2D(a); // create function
XYDataset dataset = DatasetUtilities.sampleFunction2D(p, -5.0, 5.0, 50, "Function");
final JFreeChart chart = ChartFactory.createXYLineChart("Equation","X","Y",dataset,lotOrientation.VERTICAL,true,true,false);

如何绘制这个等式? f(x) = ln(x+3)+3 和 e^x - 2*x

最佳答案

更新:Java 8 解决方案我已经离开了下面的旧解决方案。如果要绘制的函数是您不想作为单独的类维护的一次性表达式,则在 Java 8 中,您可以将 Function2D 实现为 lambda 表达式。

例如ln(x+3)+3可以写成:

double[] a = {1.0, 3.0, 3.0};
XYDataset dataset = DatasetUtilities.sampleFunction2D(v -> Math.log(a[0]* v + a[1]) + a[2], 1.0, 5.0, 50, "Function");
final JFreeChart chart = ChartFactory.createXYLineChart("Equation", "X", "Y", dataset, PlotOrientation.VERTICAL, true, true, false);

原答案:

您可以实现自己的功能来进行绘图。例如对于 ln(x+3)+3 你可以有如下内容:

public class LogLinearFunction2D implements Function2D {
//Plot ln(ax + b) + c
double a;
double b;
double c;
public LogLinearFunction2D(double[] params) {
if(params.length != 3) throw new RuntimeException("Invalid parameters, expected array count 3");
this.a = params[0];
this.b = params[1];
this.c = params[2];
}
@Override
public double getValue(double v) {
return Math.log(a* v + b) + c;
}
}

然后您可以使用它来绘制带有代码片段的函数:

    double[] a = {1.0, 1.0, -1.0};
Function2D p = new LogLinearFunction2D(a); // create function
XYDataset dataset = DatasetUtilities.sampleFunction2D(p, 1.0, 5.0, 50, "Function");
final JFreeChart chart = ChartFactory.createXYLineChart("Equation", "X", "Y", dataset, PlotOrientation.VERTICAL, true, true, false);
ChartUtilities.saveChartAsPNG(new File("test.png"), chart, 500, 500);

e^x - 2*x 类似,您可以将以下 Function2D 实现概括为绘制 a*e^x + b*x + c 并传递数组 double[] a = {1.0, -2.0, 0}

private static class ExpLinearFunction2D implements Function2D {
//Plot a*e^x + b*x + c
double a;
double b;
double c;
public ExpLinearFunction2D(double[] params) {
if(params.length != 3) throw new RuntimeException("Invalid parameters, expected array count 3");
this.a = params[0];
this.b = params[1];
this.c = params[2];
}
@Override
public double getValue(double v) {
return a * Math.exp(v) + b * v + c;
}
}

关于java - JFreeChart 绘制自然对数和 e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com