Skip to content

Instantly share code, notes, and snippets.

@ROki1988
Last active August 3, 2017 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ROki1988/473ec34f56469ff739774358042853c4 to your computer and use it in GitHub Desktop.
Save ROki1988/473ec34f56469ff739774358042853c4 to your computer and use it in GitHub Desktop.
InnerProduct
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections,
System.Math;
function InnerProduct(const Vec1: TList<Double>; const Vec2: TList<Double>): Double;
var
Scalar: TList<Double>;
Enum1: TList<Double>.TEnumerator;
Enum2: TList<Double>.TEnumerator;
begin
if Vec1.Count <> Vec2.Count then
begin
raise Exception.Create('Not match dimensions');
end;
try
Scalar := nil;
Enum1 := nil;
Enum2 := nil;
Scalar := TList<Double>.Create();
Enum1 := Vec1.GetEnumerator;
Enum2 := Vec2.GetEnumerator;
while Enum1.MoveNext and Enum2.MoveNext do
begin
Scalar.Add(Enum1.Current * Enum2.Current);
end;
Result := Sum(Scalar.List);
finally
FreeAndNil(Enum1);
FreeAndNil(Enum2);
FreeAndNil(Scalar);
end;
end;
var
Vec1: TList<Double>;
Vec2: TList<Double>;
DevNull: string;
begin
try
try
Vec1 := TList<Double>.Create();
Vec2 := TList<Double>.Create();
Vec1.AddRange([1, 2, 3]);
Vec2.AddRange([4, 5, 6]);
Writeln(InnerProduct(Vec1, Vec2).ToString);
Read(DevNull);
finally
FreeAndNil(Vec2);
FreeAndNil(Vec1);
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment