Классы, которые имеют естественный порядок сортировки (например, номер класса), должны реализовать интерфейс Comparable, в то время как классы, которые не имеют естественного порядка сортировки (например, класс-класс), должны быть снабжены компаратором (или анонимный класс компаратора).
Два примера:
public class Number implements Comparable<Number> {
private int value;
public Number(int value) { this.value = value; }
public int compareTo(Number anotherInstance) {
return this.value - anotherInstance.value;
}
}
public class Chair {
private int weight;
private int height;
public Chair(int weight, int height) {
this.weight = weight;
this.height = height;
}
/* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
public int compare(Chair chair1, Chair chair2) {
return chair1.getWeight() - chair2.getWeight();
}
}
class ChairHeightComparator implements Comparator<Chair> {
public int compare(Chair chair1, Chair chair2) {
return chair1.getHeight() - chair2.getHeight();
}
}
Использование:
List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);
List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());
// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
public int compare(Chair chair1, Chair chair2) {
...
}
});
Вы забыли круглые скобки приблизительно 4*t
:
pi = (a+b)**2 / (4*t)
можно использовать decimal
для выполнения вычисления с более высокой точностью.
#!/usr/bin/env python
from __future__ import with_statement
import decimal
def pi_gauss_legendre():
D = decimal.Decimal
with decimal.localcontext() as ctx:
ctx.prec += 2
a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1
pi = None
while 1:
an = (a + b) / 2
b = (a * b).sqrt()
t -= p * (a - an) * (a - an)
a, p = an, 2*p
piold = pi
pi = (a + b) * (a + b) / (4 * t)
if pi == piold: # equal within given precision
break
return +pi
decimal.getcontext().prec = 100
print pi_gauss_legendre()
Вывод:
3.141592653589793238462643383279502884197169399375105820974944592307816406286208\
998628034825342117068
pi = (square((a+b)))/4*t
должен быть
pi = (square((a+b)))/(4*t)