Created
October 20, 2012 22:56
-
-
Save jnape/3925124 to your computer and use it in GitHub Desktop.
Leibniz formula for π using Dynamic Collections 1.2.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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