Skip to content

Instantly share code, notes, and snippets.

@jnape
Created October 20, 2012 22:56
Show Gist options
  • Save jnape/3925124 to your computer and use it in GitHub Desktop.
Save jnape/3925124 to your computer and use it in GitHub Desktop.
Leibniz formula for π using Dynamic Collections 1.2.8
package com.jnape.dynamiccollection;
import com.jnape.dynamiccollection.lambda.Function;
import com.jnape.dynamiccollection.list.DynamicList;
import static com.jnape.dynamiccollection.lambda.library.numeric.accumulator.Add.plus;
import static com.jnape.dynamiccollection.lambda.library.numeric.accumulator.Subtract.minus;
import static com.jnape.dynamiccollection.list.NumericDynamicArrayList.fromTo;
public class LeibnizSeries {
public static void main(String[] args) {
Number pi = convergenceAfterNTerms(1000000);
System.out.println(pi);
}
private static Number convergenceAfterNTerms(int n) {
return fromTo(0, n).map(toTerm()).inGroupsOf(2).map(toDifference()).reduce(plus());
}
private static Function<Number, Number> toTerm() {
return new Function<Number, Number>() {
@Override
public Number apply(Number number) {
float divisorAtIndex = number.floatValue() + number.floatValue() + 1
return 4 / divisorAtIndex;
}
};
}
private static Function<DynamicList<Number>, Number> toDifference() {
return new Function<DynamicList<Number>, Number>() {
@Override
public Number apply(DynamicList<Number> numbers) {
return numbers.reduce(minus());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment