C# 画正太分布
时间: 2023-07-12 19:13:28 浏览: 58
要画正态分布曲线,可以使用C#的Math库中的Erf函数,其可以计算误差函数,进而计算正态分布函数。以下是一个简单的示例代码:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class NormalDistribution : Form
{
private const int margin = 20;
private const int width = 500;
private const int height = 300;
private const int samples = 1000;
public NormalDistribution()
{
Text = "Normal Distribution";
Size = new Size(width + 2 * margin, height + 2 * margin);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Red, 2);
Font font = new Font("Arial", 10);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
float[] x = new float[samples];
float[] y = new float[samples];
float min = -3.0f;
float max = 3.0f;
float step = (max - min) / samples;
for (int i = 0; i < samples; i++)
{
x[i] = min + i * step;
y[i] = (float)(Math.Exp(-x[i] * x[i] / 2) / Math.Sqrt(2 * Math.PI));
}
float scaleX = width / (max - min);
float scaleY = height / y[0];
g.TranslateTransform(margin, margin + height);
g.ScaleTransform(scaleX, -scaleY);
g.DrawLines(pen, x, y);
g.ResetTransform();
g.DrawString("μ = 0, σ = 1", font, Brushes.Black, margin + width / 2, margin + height + 5, format);
g.DrawString("x", font, Brushes.Black, margin + width - 10, margin + height + 5, format);
g.DrawString("y", font, Brushes.Black, margin - 20, margin + height / 2, format);
}
public static void Main()
{
Application.Run(new NormalDistribution());
}
}
```
该代码使用了Graphics类的一些属性和方法来绘制正态分布曲线。运行上述代码,将会得到一个简单的窗口,窗口中心的红线即为所求的正态分布曲线。