-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBigNewtonRaphsonMethod.java
More file actions
75 lines (61 loc) · 2.45 KB
/
BigNewtonRaphsonMethod.java
File metadata and controls
75 lines (61 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package de.ertlu.rob.MathEx;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
public abstract class BigNewtonRaphsonMethod {
public static class NthRootNewtonRaphsonSolver extends BigNewtonRaphsonMethod {
private BigDecimal radicand;
private BigInteger degree;
public BigDecimal f(BigDecimal x) {
return MathEx.raise(x, degree).subtract(radicand);
}
public BigDecimal fPrime(BigDecimal x) {
return (new BigDecimal(degree)).multiply(MathEx.raise(x,degree.subtract(MathEx.BI_1)));
}
public BigDecimal solve(BigDecimal radicand, BigInteger degree) {
return solve(radicand, degree, MathEx.BD_1, MathEx.defaultScale, MathEx.defaultRoundingMode);
}
public BigDecimal solve(BigDecimal radicand, BigInteger degree, BigDecimal guess, int scale, RoundingMode roundingMode) {
synchronized (dataLock) {
this.radicand = radicand;
this.degree = degree;
return solveLoop(guess, scale, roundingMode);
}
}
}
public static class LogarithmNewtonRaphsonSolver extends BigNewtonRaphsonMethod {
private BigDecimal value;
@Override
BigDecimal f(BigDecimal x) {
return BigPowerSeries.Exponential.f(x).subtract(value);
}
@Override
BigDecimal fPrime(BigDecimal x) {
return BigPowerSeries.Exponential.f(x);
}
public BigDecimal solve(BigDecimal value) {
return solve(value, MathEx.BD_1, MathEx.defaultScale, MathEx.defaultRoundingMode);
}
public BigDecimal solve(BigDecimal value, BigDecimal guess, int scale, RoundingMode roundingMode) {
synchronized (dataLock) {
this.value = value;
return solveLoop(guess, scale, roundingMode);
}
}
}
public static final NthRootNewtonRaphsonSolver NthRoot = new NthRootNewtonRaphsonSolver();
public static final LogarithmNewtonRaphsonSolver Logarithm = new LogarithmNewtonRaphsonSolver();
protected final Object dataLock = new Object();
abstract BigDecimal f(BigDecimal x);
abstract BigDecimal fPrime(BigDecimal x);
protected BigDecimal solveLoop(BigDecimal guess, int scale, RoundingMode roundingMode) {
BigDecimal lastGuess = null;
BigDecimal change;
while ( lastGuess == null || lastGuess.setScale(scale, roundingMode).compareTo(guess.setScale(scale, roundingMode)) != 0 ) {
change = f(guess).divide(fPrime(guess), scale * 2, roundingMode);
lastGuess = guess;
guess = guess.subtract(change);
}
return guess;
}
}