Repository navigation
Expand file tree
/
Copy pathEntity.Continuous.Real.Definition.cs
More file actions
298 lines (253 loc) · 16 KB
/
Copy pathEntity.Continuous.Real.Definition.cs
File metadata and controls
298 lines (253 loc) · 16 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//
// Copyright (c) 2019-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using PeterO.Numbers;
namespace AngouriMath
{
partial record Entity
{
partial record Number
{
/// <summary>
/// Represents a real number, such complex
/// that its imaginary part equals 0
/// </summary>
#pragma warning disable SealedOrAbstract // The only few exceptions: Complex, Real, Rational
public partial record Real : Complex, System.IComparable<Real>
#pragma warning restore SealedOrAbstract // AMAnalyzer
{
/// <summary>
/// Constructor does not downcast automatically. Use <see cref="Create(EDecimal)"/> for automatic downcasting.
/// </summary>
private protected Real(EDecimal @decimal) : base(null, null) => storedDecimal = @decimal;
/// <summary>A rational holds no decimal of its own; it writes one out when asked.</summary>
private protected Real() : base(null, null) { }
/// <summary>
/// The PeterO number representation in <see cref="PeterO.Numbers.EDecimal"/>
/// </summary>
public virtual EDecimal EDecimal => storedDecimal!;
private readonly EDecimal? storedDecimal;
/// <summary>
/// Deconstructs as record
/// </summary>
public void Deconstruct(out EDecimal @decimal) => @decimal = EDecimal;
/// <inheritdoc/>
public override Real RealPart => this;
internal override Priority Priority => EDecimal.IsNegative ? Priority.Sum : Priority.Leaf;
/// <inheritdoc/>
public override bool IsExact => !EDecimal.IsFinite;
/// <summary>Strictly less than 0</summary>
public bool IsNegative => EDecimal.IsNegative;
/// <summary>Strictly greater than 0</summary>
public bool IsPositive => !EDecimal.IsNegative && !EDecimal.IsZero;
/// <summary>
/// Creates an instance of Real
/// (one can do it by implicit conversation)
/// </summary>
public static Real Create(EDecimal value)
{
if (!MathS.Settings.DowncastingEnabled)
return new Real(value);
if (!value.IsFinite)
return new Real(value);
// Decided cheaply before the hundred-digit splitting and the search below:
// a value that is not near any small rational -- which is what an
// evaluation produces at almost every node -- is a Real and nothing else.
// https://github.com/asc-community/AngouriMath/issues/1338
if (!Rational.MayBeASmallRational(value, MathS.Settings.FloatToRationalIterCount, MathS.Settings.DowncastingToleranceAsDouble))
return new Real(value);
var (intPart, intRest) = value.SplitDecimal();
// If the difference between value & round(value) is zero (see Number.IsZero), we consider value as an integer
var tolerance = MathS.Settings.DowncastingTolerance;
if (intRest.LessThan(tolerance))
return Integer.Create(intPart);
if (intRest.GreaterThan(1 - tolerance))
return Integer.Create(intPart.Increment());
var attempt = Rational.FindRational(value);
if (attempt is null ||
attempt.ERational.Numerator.Abs() > MathS.Settings.MaxAbsNumeratorOrDenominatorValue ||
attempt.ERational.Denominator.Abs() > MathS.Settings.MaxAbsNumeratorOrDenominatorValue)
return new Real(value);
else
return attempt;
}
/// <inheritdoc/>
public override Real Abs() => Create(EDecimal.Abs());
internal static bool TryParse(string s,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Real? dst)
{
// PeterO.Numbers has no TryParse; FromString throws FormatException for a string
// that is not a number, and nothing else is caught.
try
{
dst = EDecimal.FromString(s);
return true;
}
catch (System.FormatException)
{
dst = null;
return false;
}
}
/// <summary>Negative Infinity (-oo)</summary>
[ConstantField] public static readonly Real NegativeInfinity = new Real(EDecimal.NegativeInfinity);
/// <summary>Positive Infinity (+oo)</summary>
[ConstantField] public static readonly Real PositiveInfinity = new Real(EDecimal.PositiveInfinity);
/// <summary>Not A Number (NaN)</summary>
[ConstantField] public static readonly Real NaN = new Real(EDecimal.NaN);
/// <summary>
/// Converts the given number to a double (not recommended in general unless you need a built-in type)
/// </summary>
public double AsDouble() => EDecimal.ToDouble();
// Comparison here is on the value and answers a bool, unlike the operators on
// Entity, which build an inequality node to be solved or evaluated later.
//
// The four operators refuse NaN: every one of them is false when either side is
// NaN, as with double. CompareTo below deliberately does not, because sorting
// needs a total order and an operator does not. See
// https://github.com/asc-community/AngouriMath/issues/947 -- these used to order
// NaN above every number, so `NaN > 1` was true and a guard reading
// `if (value > threshold)` treated an undefined value as exceeding the threshold,
// which is the least safe of the two available defaults.
/// <summary>
/// Whether the first is strictly greater, and <see langword="false"/> where
/// either is <see cref="NaN"/>.
/// </summary>
/// <remarks>
/// A comparison against <see cref="NaN"/> is false in both directions, as with
/// <see langword="double"/>: <c>NaN > x</c> and <c>x > NaN</c> are both
/// false, and so are the other three operators. "Not a number" is not a position
/// in the order, so asking where it sits has no true answer to give.
/// <see cref="CompareTo(Real)"/> answers a different question and still orders it.
/// </remarks>
public static bool operator >(Real a, Real b)
=> !a.IsNaN && !b.IsNaN && a.EDecimal.GreaterThan(b.EDecimal);
/// <summary>
/// Whether the first is greater or they are equal, and <see langword="false"/>
/// where either is <see cref="NaN"/> -- including <c>NaN >= NaN</c>.
/// </summary>
public static bool operator >=(Real a, Real b)
=> !a.IsNaN && !b.IsNaN && a.EDecimal.GreaterThanOrEquals(b.EDecimal);
/// <summary>
/// Whether the first is strictly less, and <see langword="false"/> where either
/// is <see cref="NaN"/>. See <see cref="op_GreaterThan(Real, Real)"/>.
/// </summary>
public static bool operator <(Real a, Real b)
=> !a.IsNaN && !b.IsNaN && a.EDecimal.LessThan(b.EDecimal);
/// <summary>
/// Whether the first is less or they are equal, and <see langword="false"/> where
/// either is <see cref="NaN"/> -- including <c>NaN <= NaN</c>.
/// </summary>
public static bool operator <=(Real a, Real b)
=> !a.IsNaN && !b.IsNaN && a.EDecimal.LessThanOrEquals(b.EDecimal);
/// <summary>
/// Negative, zero or positive as this is less than, equal to or greater than
/// <paramref name="other"/>, which is what sorting wants.
/// </summary>
/// <remarks>
/// <b>This orders <see cref="NaN"/> and the operators do not</b>, which is
/// deliberate rather than an inconsistency left behind. Sorting requires a total
/// order -- <see cref="System.Array.Sort(System.Array)"/> may loop or throw
/// without one -- so <see cref="NaN"/> has to sort somewhere, and it sorts above
/// every number. "Where does this sort" and "is this greater" are different
/// questions, and only the second has no answer for a value that is not a number.
/// See https://github.com/asc-community/AngouriMath/issues/947.
/// </remarks>
/// <exception cref="System.ArgumentNullException">
/// Thrown where <paramref name="other"/> is <see langword="null"/>. Unlike
/// <see cref="System.IComparable{T}"/>'s usual contract, null does not sort first
/// here; it is refused.
/// </exception>
public int CompareTo(Real? other) => other is null ? throw new System.ArgumentNullException() : EDecimal.CompareTo(other.EDecimal);
/// <summary>Their sum, computed.</summary>
public static Real operator +(Real a, Real b) => OpSum(a, b);
/// <summary>Their difference, computed.</summary>
public static Real operator -(Real a, Real b) => OpSub(a, b);
/// <summary>Their product, computed.</summary>
public static Real operator *(Real a, Real b) => OpMul(a, b);
/// <summary>
/// Their quotient, computed. Division by zero gives <see cref="NaN"/> rather
/// than throwing, so a quotient always has an answer of some kind.
/// </summary>
public static Real operator /(Real a, Real b) => OpDiv(a, b).Downcast<Real>();
/// <summary>The operand itself; unary plus changes nothing.</summary>
public static Real operator +(Real a) => a;
/// <summary>Its negation, computed.</summary>
public static Real operator -(Real a) => OpMul(Integer.MinusOne, a);
/// <summary>
/// The floored remainder, which takes the sign of the divisor: -7 % 3 is 2 and
/// 7 % (-3) is -2. See https://github.com/asc-community/AngouriMath/issues/708.
/// </summary>
/// <remarks>
/// This one used to truncate and so took the sign of the dividend, disagreeing
/// with the same operator on <see cref="Integer"/> and on
/// <see cref="Rational"/> -- which one applied depended on the static type at
/// the call site rather than on the values.
/// </remarks>
public static Real operator %(Real a, Real b)
=> a.EDecimal.Remainder(b.EDecimal, MathS.Settings.DecimalPrecisionContext)
.Alias(out var truncated)
.IsZero || truncated.IsNegative == b.EDecimal.IsNegative
? truncated
: truncated.Add(b.EDecimal, MathS.Settings.DecimalPrecisionContext);
// With MathS.Settings.DowncastingEnabled, which is the default, a value that is
// exactly whole arrives as an Integer and one that is exactly a ratio as a
// Rational. The declared type is Real either way, so the difference is in the
// runtime type and in how the number prints, not in the signature.
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(sbyte value) => (long)value;
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(byte value) => (ulong)value;
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(short value) => (long)value;
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(ushort value) => (ulong)value;
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(int value) => (long)value;
/// <summary>The number as a <see cref="Real"/>.</summary>
public static implicit operator Real(uint value) => (ulong)value;
/// <summary>
/// The number as a <see cref="Real"/> — an <see cref="Integer"/> at runtime
/// while downcasting is enabled.
/// </summary>
public static implicit operator Real(long value) => MathS.Settings.DowncastingEnabled ? Integer.Create(value) : new Real(value);
/// <summary>
/// The number as a <see cref="Real"/> — an <see cref="Integer"/> at runtime
/// while downcasting is enabled.
/// </summary>
public static implicit operator Real(ulong value) => MathS.Settings.DowncastingEnabled ? Integer.Create(value) : new Real(value);
/// <summary>
/// The integer as a <see cref="Real"/> — an <see cref="Integer"/> at runtime
/// while downcasting is enabled.
/// </summary>
public static implicit operator Real(EInteger value) => MathS.Settings.DowncastingEnabled ? Integer.Create(value) : new Real(value);
/// <summary>
/// The ratio as a <see cref="Real"/>. While downcasting is enabled it stays a
/// <see cref="Rational"/> and so stays exact; with it off the ratio is evaluated
/// to the working precision and a third becomes a finite decimal.
/// </summary>
public static implicit operator Real(ERational value) => MathS.Settings.DowncastingEnabled ? Rational.Create(value) : Create(value.ToEDecimal(MathS.Settings.DecimalPrecisionContext));
/// <summary>The decimal as a <see cref="Real"/>.</summary>
public static implicit operator Real(EDecimal value) => Create(value);
/// <summary>
/// The value as a <see cref="Real"/>, read as the binary <see langword="float"/>
/// it is — so <c>0.1f</c> becomes the value that literal holds, not one tenth.
/// </summary>
public static implicit operator Real(float value) => Create(EDecimal.FromSingle(value));
/// <summary>
/// The value as a <see cref="Real"/>, read as the binary
/// <see langword="double"/> it is rather than as the decimal it was written as.
/// </summary>
public static implicit operator Real(double value) => Create(EDecimal.FromDouble(value));
/// <summary>
/// The value as a <see cref="Real"/>. A <see langword="decimal"/> is decimal
/// already, so this one keeps the digits that were written.
/// </summary>
public static implicit operator Real(decimal value) => Create(EDecimal.FromDecimal(value));
}
}
}
}