Skip to content

Commit

Permalink
Validate inputs for safe logarithm calculation (#8439)
Browse files Browse the repository at this point in the history
- Ensure both previousPoint and previousPoint2 are non-zero.
- Prevent division by zero and undefined errors.
- Add unit test to verity the new validation logic.
  • Loading branch information
JosueNina authored Dec 3, 2024
1 parent a28d1f2 commit 8123e76
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
7 changes: 4 additions & 3 deletions Indicators/AugenPriceSpike.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public AugenPriceSpike(string name, int period)
}
_standardDeviation = new StandardDeviation(period);
_rollingData = new RollingWindow<decimal>(3);
WarmUpPeriod = period+2;
WarmUpPeriod = period + 2;
}

/// <summary>
Expand All @@ -91,9 +91,10 @@ protected override decimal ComputeNextValue(IndicatorDataPoint input)
var previousPoint2 = _rollingData[2];

var logPoint = 0.0;
if (previousPoint2 != 0)
// Ensure the logarithm operation is valid, as log(0) is undefined, and avoid division by zero.
if (previousPoint != 0 && previousPoint2 != 0)
{
logPoint = Math.Log((double)(previousPoint / previousPoint2));
logPoint = Math.Log((double)previousPoint / (double)previousPoint2);
}

_standardDeviation.Update(input.Time, (decimal)logPoint);
Expand Down
21 changes: 21 additions & 0 deletions Tests/Indicators/AugenPriceSpikeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,26 @@ public override void ResetsProperly()
aps.Reset();
TestHelper.AssertIndicatorIsInDefaultState(aps);
}

[Test]
public void DoesNotThrowOverflowException()
{
var aps = new AugenPriceSpike(5);
var values = new List<decimal>
{
decimal.MaxValue,
0,
1e-18m,
decimal.MaxValue,
1m
};

var date = new DateTime(2024, 12, 2, 12, 0, 0);

for (var i = 0; i < values.Count; i++)
{
Assert.DoesNotThrow(() => aps.Update(date, values[i]));
}
}
}
}

0 comments on commit 8123e76

Please sign in to comment.