Last active
August 3, 2017 00:58
-
-
Save ROki1988/473ec34f56469ff739774358042853c4 to your computer and use it in GitHub Desktop.
InnerProduct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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