- رسم یک تابع روی محور های دکارتی
خیلی پیش میاد که بخواهیم تو کارهای تحقیقاتی یا برنامه های گرافیکی تحلیلی یک نمودار از تابع خاصی بسازیم.
منظور من از نمودار مثلا میله ای یا کیکی نیست، منظور نمودار های ریاضی هستند که توابعی رو Plot می کنند.
قطعه کدی که ارائه می شه هسته ی این جور کارهاست که شما می تونید با توجه به نیازتون اصلاحش کنید.
می تونید یک Parser کوچیک بهش اضافه کنید تا از یک ادیت تابع رو از یوزر بگیره، یا برای اون قسمت می تونید از PascalScript کمک بگیرید.
کد:
type
TFuncForPlot = function(x: real): real;
function Fx1(x: real): real;
begin
Result := sin(x);
end;
function Fx2(x: real): real;
begin
Result := x / exp(x*x);
end;
procedure Plot(ACanvas: TCanvas; AWidth, AHeight: integer; AFunction: TFuncForPlot; Scale: integer; AColor: TColor);
var
pos: real;
y: real;
lastPoint, thisPoint: TPoint;
begin
ACanvas.Pen.Color := clGray;
ACanvas.MoveTo(0, AHeight div 2);
ACanvas.LineTo(AWidth, AHeight div 2);
ACanvas.MoveTo(AWidth div 2, 0);
ACanvas.LineTo(AWidth div 2, AHeight);
ACanvas.Pen.Color := AColor;
pos := -AWidth / Scale / 2;
lastPoint := Point(-MaxInt, 0);
repeat
y := AFunction(pos);
thisPoint := Point(AWidth div 2 + round(pos * Scale), AHeight div 2 - round(y * Scale));
ACanvas.MoveTo(lastPoint.X, lastPoint.Y);
ACanvas.LineTo(thisPoint.X, thisPoint.Y);
lastPoint := thisPoint;
pos := pos + (1 / Scale);
until pos >= AWidth / Scale / 2;
end;
مثال:
Plot(Image1.Canvas, Image1.Width, Image1.Height, Fx1, 20, clRed);
Plot(Image1.Canvas, Image1.Width, Image1.Height, Fx2, 100, clBlue);