sync from Atlas repo
This commit is contained in:
26
operator/Interest.java
Normal file
26
operator/Interest.java
Normal file
@@ -0,0 +1,26 @@
|
||||
/***
|
||||
Compound interest function with ``BigDecimal``
|
||||
|
||||
Equivalent in Python:
|
||||
|
||||
def compound_interest(principal, rate, periods):
|
||||
return principal * ((1 + rate) ** periods - 1)
|
||||
|
||||
***/
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class Interest {
|
||||
|
||||
static BigDecimal compoundInterest(BigDecimal principal, BigDecimal rate, int periods) {
|
||||
return principal.multiply(BigDecimal.ONE.add(rate).pow(periods).subtract(BigDecimal.ONE));
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
BigDecimal principal = new BigDecimal(1000);
|
||||
BigDecimal rate = new BigDecimal("0.06");
|
||||
int periods = 5;
|
||||
System.out.println(compoundInterest(principal, rate, periods));
|
||||
}
|
||||
|
||||
}
|
||||
17
operator/dispatch.py
Normal file
17
operator/dispatch.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""
|
||||
Experiments with infix operator dispatch
|
||||
|
||||
>>> kadd = KnowsAdd()
|
||||
>>> kadd + 1
|
||||
(<KnowsAdd object>, 1)
|
||||
>>> kadd * 1
|
||||
|
||||
"""
|
||||
|
||||
|
||||
class KnowsAdd:
|
||||
def __add__(self, other):
|
||||
return self, other
|
||||
def __repr__(self):
|
||||
return '<{} object>'.format(type(self).__name__)
|
||||
|
||||
25
operator/interest.py
Normal file
25
operator/interest.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
Compound interest function with ``decimal.Decimal``
|
||||
|
||||
"""
|
||||
|
||||
def compound_interest(principal, rate, periods):
|
||||
return principal * ((1 + rate) ** periods - 1)
|
||||
|
||||
def test(verbose=False):
|
||||
from decimal import Decimal, getcontext
|
||||
getcontext().prec = 8
|
||||
fixture = [(1000, Decimal('0.05'), 1, Decimal('50')),
|
||||
(1000, Decimal('0.10'), 5, Decimal('610.51')),
|
||||
(1000, Decimal('0.10'), 15, Decimal('3177.2482')),
|
||||
(1000, Decimal('0.06'), 5, Decimal('338.2256')),
|
||||
]
|
||||
for principal, rate, periods, future_value in fixture:
|
||||
computed = compound_interest(principal, rate, periods)
|
||||
if verbose:
|
||||
print('{!r}, {!r}, {!r} -> {!r}'.format(
|
||||
principal, rate, periods, computed))
|
||||
assert future_value == computed, '{!r} != {!r}'.format(future_value, computed)
|
||||
|
||||
if __name__ == '__main__':
|
||||
test(True)
|
||||
Reference in New Issue
Block a user