Skip to content

Add function to normalise a set of weight values so that they sum to 1 #44

Closed
@delphidabbler

Description

@delphidabbler

The following routine is proposed:

function NormaliseByWeight(const Weights: array of Double):
  Types.TDoubleDynArray;
var
  Weight: Double;
  WeightSum: Double;
  Idx: Integer;
begin
  if (System.Length(Weights) = 0) then
    raise SysUtils.EArgumentException.Create('Array of weights is empty');
  WeightSum := 0.0;
  for Weight in Weights do
  begin
    if Math.Sign(Weight) = Math.NegativeValue then
      raise SysUtils.EArgumentException.Create('Weights must all be >= 0');
    WeightSum := WeightSum + Weight;
  end;
  if Math.IsZero(WeightSum) then
    raise SysUtils.EArgumentException.Create('Sum of weights can''t be zero');
  System.SetLength(Result, System.Length(Weights));
  for Idx := 0 to Pred(System.Length(Weights)) do
    Result[Idx] := Weights[Idx] / WeightSum;
end;

Metadata

Metadata

Assignees

Labels

completedIssue completed and committed to develop. To be closed on next releaseenhancementNew feature or request

Projects

Status

Completed

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions