View Javadoc
1   package com.github.davidmoten.rx;
2   
3   import rx.Observable;
4   import rx.functions.Func0;
5   import rx.functions.Func1;
6   import rx.functions.Func2;
7   
8   public final class Maths {
9   
10      private Maths() {
11          // prevent instantiation
12      }
13  
14      public static Observable<Double> solveWithNewtonsMethod(final Func1<Double, Double> f,
15              final Func1<Double, Double> dfdx, double x0) {
16          return Observable.just(1).repeat().scan(x0, new Func2<Double, Integer, Double>() {
17              @Override
18              public Double call(Double xn, Integer n) {
19                  return xn - f.call(xn) / dfdx.call(xn);
20              }
21          });
22      }
23  
24      public static Observable<Double> solveWithNewtonsMethod(final Func1<Double, Double> f,
25              final double x0, final double h) {
26          Func1<Double, Double> dfdx = new Func1<Double, Double>() {
27              @Override
28              public Double call(Double x) {
29                  return (f.call(x + h) - f.call(x - h)) / 2.0 / h;
30              }
31          };
32          return solveWithNewtonsMethod(f, dfdx, x0);
33      }
34  
35      public static Observable<Long> primes() {
36          return Observable.defer(new Func0<Observable<Long>>() {
37              final Mutable<Long> n = new Mutable<Long>(0L);
38  
39              @Override
40              public Observable<Long> call() {
41                  return Observable.just(1).repeat().map(new Func1<Integer, Long>() {
42                      @Override
43                      public Long call(Integer t) {
44                          n.value += 1;
45                          return n.value;
46                      }
47                  });
48              }
49          }).filter(new Func1<Long, Boolean>() {
50  
51              @Override
52              public Boolean call(Long n) {
53                  if (n < 2) {
54                      return false;
55                  }
56                  for (int i = 2; i <= Math.floor(Math.sqrt(n)); i++) {
57                      if (n % i == 0) {
58                          return false;
59                      }
60                  }
61                  return true;
62              }
63          });
64      }
65  
66      private static final class Mutable<T> {
67          T value;
68  
69          Mutable(T value) {
70              this.value = value;
71          }
72  
73      }
74  
75  }