Repository navigation
fix(maths): handle negative exponents and prevent stack overflow in PowerUsingRecursion - #7768
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #7768 +/- ##
============================================
+ Coverage 82.59% 82.60% +0.01%
- Complexity 8605 8612 +7
============================================
Files 848 848
Lines 26460 26470 +10
Branches 5181 5185 +4
============================================
+ Hits 21854 21866 +12
Misses 3823 3823
+ Partials 783 781 -2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…owerUsingRecursion
1d529b9 to
9b53036
Compare
DenizAltunkapan
left a comment
There was a problem hiding this comment.
@spidervirus The current implementation for negative exponents can cause premature floating-point overflow:
return 1.0 / power(base, -exponent);For example, power(2.0, -1024) returns 0.0 because the intermediate result overflows to Infinity, even though the expected result is representable as a double.
Please consider using the reciprocal of the base instead of the reciprocal of the result. Make sure that Integer.MIN_VALUE is still handled correctly and add a corresponding regression test.
|
@DenizAltunkapan Thank you for the review! I have updated the implementation to compute with the reciprocal of the base ( |
|
@DenizAltunkapan Welcome |
clang-format -i --style=file path/to/your/file.javaDescription
In
com.thealgorithms.maths.PowerUsingRecursion.power(double base, int exponent):power(2.0, -3)) resulted in an infinite recursive loop causingStackOverflowError, because it decrementedexponent - 1indefinitely.StackOverflowErroron large exponents.Fix
base^(-e) = 1 / base^e.ArithmeticExceptionwhenbase == 0.0with negative exponent.Integer.MIN_VALUEsafely without integer negation overflow.O(log n)stack depth) for even exponents to avoid stack exhaustion.