update from Atlas with major reorg

This commit is contained in:
Luciano Ramalho
2015-04-17 21:29:30 -03:00
parent 57902d31b5
commit a786180239
134 changed files with 369 additions and 520 deletions

View 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));
}
}

View 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__)

View File

@@ -0,0 +1,47 @@
import java.math.BigInteger;
class CorrectFactorial {
public static BigInteger factorial(BigInteger n) {
return n.compareTo(BigInteger.ONE) <= 0 ? BigInteger.ONE
: n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static void main(String args[]) {
BigInteger upperBound = new BigInteger("25");
for (BigInteger i = BigInteger.ONE;
i.compareTo(upperBound) <= 0;
i = i.add(BigInteger.ONE)) {
System.out.println(i + "! = " + factorial(i));
}
}
}
/* output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
*/

View File

@@ -0,0 +1,43 @@
class SimpleFactorial {
public static long factorial(long n) {
return n < 2 ? 1 : n * factorial(n-1);
}
public static void main(String args[]) {
for (long i = 1; i <= 25; i++) {
System.out.println(i + "! = " + factorial(i));
}
}
}
/* output: incorrect results starting with 21!
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = -4249290049419214848
22! = -1250660718674968576
23! = 8128291617894825984
24! = -7835185981329244160
25! = 7034535277573963776
*/

View File

@@ -0,0 +1,36 @@
def factorial(n):
return 1 if n < 2 else n * factorial(n-1)
if __name__=='__main__':
for i in range(1, 26):
print('%s! = %s' % (i, factorial(i)))
"""
output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
"""

View 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)

140
attic/operator/vector.py Normal file
View File

@@ -0,0 +1,140 @@
"""
The `+` operator produces a `Vector` result.
>>> v1 = Vector(2, 4)
>>> v2 = Vector(2, 1)
>>> v1 + v2
Vector(4, 5)
We can also implemement the `*` operator to perform scalar multiplication
or elementwise multiplication.
>>> v = Vector(3, 4)
>>> abs(v)
5.0
>>> v * 3
Vector(9, 12)
>>> abs(v * 3)
15.0
>>> v25 = Vector(2, 5)
>>> v71 = Vector(7, 1)
>>> v71 * v25
Vector(14, 5)
A vector can be used in a boolean context, where it will be considered
_falsy_ if it has magnitude zero, otherwise it is _truthy_::
>>> bool(v)
True
>>> bool(Vector(0, 0))
False
Vectors can have n-dimensions::
>>> v3 = Vector(1, 2, 3)
>>> len(v3)
3
>>> v3
Vector(1, 2, 3)
>>> abs(v3) # doctest:+ELLIPSIS
3.74165738...
>>> v3 + Vector(4, 5, 6)
Vector(5, 7, 9)
>>> v3 * 5
Vector(5, 10, 15)
>>> v2 + v3
Traceback (most recent call last):
...
ValueError: Addition applies only to vectors of equal dimensions.
The `repr` of a Vector is produced with the help of the `reprlib.repr`
function, limiting the size of the output string:
>>> Vector(*range(100))
Vector(0, 1, 2, 3, 4, 5, ...)
Dot product is a scalar: the sum of the products of the corresponding
components of two vectors.
>>> v25 = Vector(2, 5)
>>> v71 = Vector(7, 1)
>>> v25.dot(v71)
19
>>> Vector(1, 2, 3).dot(Vector(4, 5, 6))
32
>>> Vector(1, 2, 3).dot(Vector(-2, 0, 5))
13
As described in PEP 465, starting with Python 3.5, `__matmul__` is
the special method for the new ``@`` operator, to be used the dot
product of vectors or matrix multiplication (as opposed to ``*``
which is intended for scalar or elementwise multiplication):
>>> # skip these tests on Python < 3.5
>>> v25 @ v71 # doctest:+SKIP
19
>>> v71 * v25
Vector(14, 5)
>>> Vector(1, 2, 3) @ Vector(-2, 0, 5) # doctest:+SKIP
13
"""
# BEGIN VECTOR_OPS
import math
import numbers
import reprlib
EQ_DIMENSIONS_MSG = '%s applies only to vectors of equal dimensions.'
class Vector:
"""An n-dimensional vector"""
def __init__(self, *components): # <1>
self._components = tuple(components) # <2>
def __repr__(self):
return 'Vector' + (reprlib.repr(self._components)) # <3>
def __iter__(self):
return iter(self._components) # <4>
def __abs__(self):
return math.sqrt(sum(comp*comp for comp in self)) # <5>
def __len__(self):
return len(self._components) # <6>
def __add__(self, other):
if len(self) != len(other):
raise ValueError(EQ_DIMENSIONS_MSG % 'Addition')
return Vector(*(a+b for a, b in zip(self, other))) # <7>
def __mul__(self, other):
if isinstance(other, numbers.Number):
return Vector(*(comp*other for comp in self)) # <8>
else:
return self.elementwise_mul(other) # <9>
def elementwise_mul(self, other):
if len(self) != len(other):
raise ValueError(EQ_DIMENSIONS_MSG %
'Elementwise multiplication')
return Vector(*(a*b for a, b in zip(self, other))) # <10>
def __bool__(self):
return any(self) # <11>
def dot(self, other):
if len(self) != len(other):
raise ValueError(EQ_DIMENSIONS_MSG %
'Dot product')
return sum(a*b for a, b in zip(self, other)) # <12>
__matmul__ = dot # support @ operator in Python 3.5
# END VECTOR_OPS