Java Language Streams Using Streams to Implement Mathematical Functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Streams, and especially IntStreams, are an elegant way of implementing summation terms (∑). The ranges of the Stream can be used as the bounds of the summation.

E.g., Madhava's approximation of Pi is given by the formula (Source: wikipedia): Madhava's approximation

This can be calculated with an arbitrary precision. E.g., for 101 terms:

double pi = Math.sqrt(12) * 
            IntStream.rangeClosed(0, 100)
                     .mapToDouble(k -> Math.pow(-3, -1 * k) / (2 * k + 1))
                     .sum();

Note: With double's precision, selecting an upper bound of 29 is sufficient to get a result that's indistinguishable from Math.Pi.



Got any Java Language Question?