forked from MadsKirkFoged/EngineeringUnits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFraction.txt
103 lines (68 loc) · 3 KB
/
Fraction.txt
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Text;
namespace Fractions {
public static class FractionExtensions
{
/// <summary>
/// Returns the square root of a fraction. Use <paramref name="numberOFDecimalPlaceAccuracy"/> to set the accuracy.
/// </summary>
/// <param name="numberOFDecimalPlaceAccuracy"></param>
public static Fraction Sqrt(this Fraction x, int numberOFDecimalPlaceAccuracy = 30) {
//Babylonian Method of computing square roots
if (x < 0) {
throw new OverflowException("Cannot calculate square root from a negative number");
}
Fraction oldGuess;
var newGuess = Fraction.Zero;
var tolerance = new Fraction(BigInteger.One, BigInteger.Pow(new BigInteger(10), numberOFDecimalPlaceAccuracy));
//Using Math.Sqrt to get a good starting guess
var guessDouble = Math.Sqrt((double)x);
if (double.IsInfinity(guessDouble)) {
oldGuess = x / 2;
} else {
oldGuess = (Fraction)guessDouble;
}
while ((oldGuess - newGuess).Abs() > tolerance) {
//Babylonian Method
newGuess = (oldGuess + (x / oldGuess)) / 2;
oldGuess = newGuess;
}
return newGuess;
}
//calculates the value of e to the power of x, where e is the base of the natural logarithm
public static Fraction Exp(this Fraction x, int accuracy = 100) {
var sum = Fraction.One;
// var tolerance = new Fraction(BigInteger.One, BigInteger.Pow(new BigInteger(10), numberOFDecimalPlaceAccuracy));
for (int i = accuracy - 1; i > 0; i--) {
sum = 1 + x * sum / i;
}
return sum;
}
public static Fraction Ln(this Fraction x, int numberOFDecimalPlaceAccuracy = 30) {
Fraction oldGuess;
var newGuess = Fraction.Zero;
var tolerance = new Fraction(BigInteger.One, BigInteger.Pow(new BigInteger(10), numberOFDecimalPlaceAccuracy));
//Using Math.Sqrt to get a good starting guess
var guessDouble = Math.Log((double)x);
if (double.IsInfinity(guessDouble)) {
oldGuess = x / 2;
} else {
oldGuess = (Fraction)guessDouble;
}
while ((oldGuess - newGuess).Abs() > tolerance) {
newGuess = oldGuess + 2 * (((x - oldGuess.Exp()) / (x + oldGuess.Exp())));
oldGuess = newGuess;
}
return oldGuess;
}
public static Fraction Pow(this Fraction x,decimal power, int numberOFDecimalPlaceAccuracy = 30) {
// fx 2.1^3.37
//--> 3.37 * Ln(2.1)
var fraction test = x.Ln(numberOFDecimalPlaceAccuracy) * (fraction)power;
return test.exp(numberOFDecimalPlaceAccuracy);
}
}
}