Home 定点数
Post
Cancel

定点数

关于浮点数 https://blog.csdn.net/jiaoyangwm/article/details/129296459

什么是定点数

定点数:

作用:

1
在帧同步过程中,需要使用浮点数,浮点数在不同平台的精度不同会产生误差,采用定点数代替浮点数来保证所以平台运算结果确定性

原理

1
2
3
4
固定计算机中小数点的位置    
整数+小数  
1.5(Int) = 1*2^32 + 5;
25.125(Int) = 25*2^32 + 125;

### 基本实现 采用 RawValue(long 64bit类型)32位整数+32位小数 Int转换位定点数 RawValue = value * 2^32; Float位定点数 RawValue = value * 2^32; - 定点数加法:RawValue+RawValue - 定点数减法:RawValue-RawValue - 定点数乘法:(RawValueRawValue)/(2^32) 实际算法需要优化 - 定点数除法:(RawValue/RawValue)(2^32) 实际算法需要优化

生成Sin 查表数据

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
 internal static void GenerateSinLut()
        {
            using (var writer = new StreamWriter("Fix64SinLut.cs"))
            {
                writer.Write(
@"namespace FixMath.NET 
{
    partial struct Fix64 
    {
        public static readonly long[] SinLut = new[] 
        {");
                int lineCounter = 0;
                for (int i = 0; i < LUT_SIZE; ++i)
                {
                    var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
                    if (lineCounter++ % 8 == 0)
                    {
                        writer.WriteLine();
                        writer.Write("            ");
                    }
                    var sin = Math.Sin(angle);
                    var rawValue = ((Fix64)sin).m_rawValue;
                    writer.Write(string.Format("0x{0:X}L, ", rawValue));
                }
                writer.Write(
@"
        };
    }
}");
            }
        }

生成Tan 查表数据

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
internal static void GenerateTanLut()
        {
            using (var writer = new StreamWriter("Fix64TanLut.cs"))
            {
                writer.Write(
@"namespace FixMath.NET 
{
    partial struct Fix64 
    {
        public static readonly long[] TanLut = new[] 
        {");
                int lineCounter = 0;
                for (int i = 0; i < LUT_SIZE; ++i)
                {
                    var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
                    if (lineCounter++ % 8 == 0)
                    {
                        writer.WriteLine();
                        writer.Write("            ");
                    }
                    var tan = Math.Tan(angle);
                    if (tan > (double)MaxValue || tan < 0.0)
                    {
                        tan = (double)MaxValue;
                    }
                    var rawValue = (((decimal)tan > (decimal)MaxValue || tan < 0.0) ? MaxValue : (Fix64)tan).m_rawValue;
                    writer.Write(string.Format("0x{0:X}L, ", rawValue));
                }
                writer.Write(
@"
        };
    }
}");
            }
        }

主函数

1
2
3
4
5
6
static void Main(string[] args)
{
    GenerateSinLut();
    GenerateTanLut();
}

Fix64.cs

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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
using System;
using System.IO;
using System.Runtime.CompilerServices;

namespace FixMath.NET
{

    /// <summary>
    /// Represents a Q31.32 fixed-point number.
    /// </summary>
    public partial struct Fix64 : IEquatable<Fix64>, IComparable<Fix64> {
		// Field is public and mutable to allow serialization by XNA Content Pipeline
        public long RawValue;

        // Precision of this type is 2^-32, that is 2,3283064365386962890625E-10
        public static readonly decimal Precision = (decimal)(new Fix64(1L));//0.00000000023283064365386962890625m;
        public static readonly Fix64 MaxValue = new Fix64(MAX_VALUE);
        public static readonly Fix64 MinValue = new Fix64(MIN_VALUE);
		public static readonly Fix64 MinusOne = new Fix64(-ONE);
		public static readonly Fix64 One = new Fix64(ONE);
		public static readonly Fix64 Two = (Fix64)2;
		public static readonly Fix64 Three = (Fix64)3;
		public static readonly Fix64 Zero = new Fix64();
		public static readonly Fix64 C0p28 = (Fix64)0.28m;
		/// <summary>
		/// The value of Pi
		/// </summary>
		public static readonly Fix64 Pi = new Fix64(PI);
        public static readonly Fix64 PiOver2 = new Fix64(PI_OVER_2);
		public static readonly Fix64 PiOver4 = new Fix64(PI_OVER_4);
		public static readonly Fix64 PiTimes2 = new Fix64(PI_TIMES_2);
        //public static readonly Fix64 PiInv = (Fix64)0.3183098861837906715377675267M;
        //public static readonly Fix64 PiOver2Inv = (Fix64)0.6366197723675813430755350535M;
		public static readonly Fix64 E = new Fix64(E_RAW);
		public static readonly Fix64 EPow4 = new Fix64(EPOW4);
		public static readonly Fix64 Ln2 = new Fix64(LN2);
		public static readonly Fix64 Log2Max = new Fix64(LOG2MAX);
		public static readonly Fix64 Log2Min = new Fix64(LOG2MIN);

		static readonly Fix64 LutInterval = (Fix64)(LUT_SIZE - 1) / PiOver2;
        const long MAX_VALUE = long.MaxValue;
        const long MIN_VALUE = long.MinValue;
        const int NUM_BITS = 64;
        //const int FRACTIONAL_PLACES = 32;
        
#if FRACTIONAL_PLACES_8 
		const int FRACTIONAL_PLACES = 8;
        const int FRACTIONAL_PLACES_VALUE = 0xFF;
	    const ulong FRACTIONAL_PLACES_VALUE1 = 0x80UL;
	    const int FRACTIONAL_PLACES_VALUE2 = 0xFFFFFFFF;
	    const long FRACTIONAL_PLACES_VALUE2 = 0xFFFFFFFF;
#elif FRACTIONAL_PLACES_16
	    const int FRACTIONAL_PLACES = 16;
        const int FRACTIONAL_PLACES_VALUE = 0xFFFF;
        const ulong FRACTIONAL_PLACES_VALUE1 = 0x8000UL;
        const long FRACTIONAL_PLACES_VALUE2 = 0xFFFF;
        const long FRACTIONAL_PLACES_VALUE3 = 0x8000L;
        const ulong FRACTIONAL_PLACES_VALUE4 = 0xFFFFFFFFFFFF0000;
        const long ONE = 1L << FRACTIONAL_PLACES;
        const long PI_TIMES_2 = 0x6487E;
        const long PI = 0x3243F;
        const long PI_OVER_2 = 0x1921F;
        const long PI_OVER_4 = 0xC90F;
        const long E_RAW = 0x2B7E1;
        const long EPOW4 = 0x369920;
        const long LN2 = 0xB172;
        const long LOG2MAX = 0x1F00000000;
        const long LOG2MIN = -0x2000000000;
        const int LUT_SIZE = (int)(PI_OVER_2 >> 6);
#else
        const int FRACTIONAL_PLACES = 32;
        const long FRACTIONAL_PLACES_VALUE = 0xFFFFFFFF;
	    const ulong FRACTIONAL_PLACES_VALUE1 = 0x80000000UL;
		const long FRACTIONAL_PLACES_VALUE2 = 0xFFFFFFFF;
		const long FRACTIONAL_PLACES_VALUE3 = 0x80000000L;
		const ulong FRACTIONAL_PLACES_VALUE4 = 0xFFFFFFFF00000000;
		const long ONE = 1L << FRACTIONAL_PLACES;
        const long PI_TIMES_2 = 0x6487ED511;
        const long PI = 0x3243F6A88;
        const long PI_OVER_2 = 0x1921FB544;
		const long PI_OVER_4 = 0xC90FDAA2;
		const long E_RAW = 0x2B7E15162;
		const long EPOW4 = 0x3699205C4E;
		const long LN2 = 0xB17217F7;
		const long LOG2MAX = 0x1F00000000;
		const long LOG2MIN = -0x2000000000;
		const int LUT_SIZE = (int)(PI_OVER_2 >> 15);
#endif
       


		/// <summary>
		/// Returns a number indicating the sign of a Fix64 number.
		/// Returns 1 if the value is positive, 0 if is 0, and -1 if it is negative.
		/// </summary>
		public static int SignI(Fix64 value) {
            return
                value.RawValue < 0 ? -1 :
                value.RawValue > 0 ? 1 :
                0;
        }

		public static Fix64 Sign(Fix64 v)
		{
			long raw = v.RawValue;
			return
				raw < 0 ? MinusOne :
				raw > 0 ? One :
				Fix64.Zero;
		}


		/// <summary>
		/// Returns the absolute value of a Fix64 number.
		/// Note: Abs(Fix64.MinValue) == Fix64.MaxValue.
		/// </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Fix64 Abs(Fix64 value) {
            if (value.RawValue == MIN_VALUE) {
                return MaxValue;
            }

            // branchless implementation, see http://www.strchr.com/optimized_abs_function
            var mask = value.RawValue >> 63;
            return new Fix64((value.RawValue + mask) ^ mask);
        }

        /// <summary>
        /// Returns the largest integer less than or equal to the specified number.
        /// </summary>
        public static Fix64 Floor(Fix64 value) {
            // Just zero out the fractional part
            return new Fix64((long)((ulong)value.RawValue & FRACTIONAL_PLACES_VALUE4));
        }

		public static Fix64 Log2(Fix64 x)
		{
			if (x.RawValue <= 0)
				throw new ArgumentOutOfRangeException("Non-positive value passed to Ln", "x");

			// This implementation is based on Clay. S. Turner's fast binary logarithm
			// algorithm[1].

			long b = 1U << (FRACTIONAL_PLACES - 1);
			long y = 0;

			long rawX = x.RawValue;
			while (rawX < ONE)
			{
				rawX <<= 1;
				y -= ONE;
			}

			while (rawX >= (ONE << 1))
			{
				rawX >>= 1;
				y += ONE;
			}

			Fix64 z = Fix64.FromRaw(rawX);

			for (int i = 0; i < FRACTIONAL_PLACES; i++)
			{
				z = z * z;
				if (z.RawValue >= (ONE << 1))
				{
					z = Fix64.FromRaw(z.RawValue >> 1);
					y += b;
				}
				b >>= 1;
			}

			return Fix64.FromRaw(y);
		}

		public static Fix64 Ln(Fix64 x)
		{
			return Log2(x) * Ln2;
		}

		public static Fix64 Pow2(Fix64 x)
		{
			if (x.RawValue == 0) return One;

			// Avoid negative arguments by exploiting that exp(-x) = 1/exp(x).
			bool neg = (x.RawValue < 0);
			if (neg) x = -x;

			if (x == One)
				return neg ? One / Two : Two;
			if (x >= Log2Max) return neg ? One / MaxValue : MaxValue;
			if (x <= Log2Min) return neg ? MaxValue : Zero;

			/* The algorithm is based on the power series for exp(x):
             * http://en.wikipedia.org/wiki/Exponential_function#Formal_definition
             * 
             * From term n, we get term n+1 by multiplying with x/n.
             * When the sum term drops to zero, we can stop summing.
             */

			int integerPart = (int)Floor(x);
			x = FractionalPart(x);

			Fix64 result = One;
			Fix64 term = One;
			int i = 1;
			while (term.RawValue != 0)
			{
				term = x * term * Ln2 / (Fix64)i;
				result += term;
				i++;
			}

			result = FromRaw(result.RawValue << integerPart);
			if (neg) result = One / result;

			return result;
		}

		public static Fix64 PowInt(int b, int exp)
		{
			return (Fix64)(Math.Pow(b, exp));
		}
		public static Fix64 Pow(Fix64 b, Fix64 exp)
		{
			if (b == One)
				return One;
			if (exp.RawValue == 0)
				return One;
			if (b.RawValue == 0)
				return Zero;

			Fix64 log2 = Log2(b);
			return Pow2(SafeMul(exp, log2));
		}

		/// <summary>
		/// Returns the arccos of of the specified number, calculated using Atan and Sqrt
		/// </summary>
		public static Fix64 Acos(Fix64 x)
		{
			if (x.RawValue == 0)
				return Fix64.PiOver2;

			Fix64 result = Fix64.Atan(Fix64.Sqrt(One - x * x) / x);
			if (x.RawValue < 0)
				return result + Fix64.Pi;
			else
				return result;
		}

		/// <summary>
		/// Returns the smallest integral value that is greater than or equal to the specified number.
		/// </summary>
		public static Fix64 Ceiling(Fix64 value) {
            var hasFractionalPart = (value.RawValue & FRACTIONAL_PLACES_VALUE2) != 0;
            return hasFractionalPart ? Floor(value) + One : value;
        }

		/// <summary>
		/// Returns the fractional part of the specified number.
		/// </summary>
		public static Fix64 FractionalPart(Fix64 value)
		{
			return Fix64.FromRaw(value.RawValue & FRACTIONAL_PLACES_VALUE2);
		}

		/// <summary>
		/// Rounds a value to the nearest integral value.
		/// If the value is halfway between an even and an uneven value, returns the even value.
		/// </summary>
		public static Fix64 Round(Fix64 value) {
            var fractionalPart = value.RawValue & FRACTIONAL_PLACES_VALUE2;
            var integralPart = Floor(value);
            if (fractionalPart < FRACTIONAL_PLACES_VALUE3) {
                return integralPart;
            }
            if (fractionalPart > FRACTIONAL_PLACES_VALUE3) {
                return integralPart + One;
            }
            // if number is halfway between two values, round to the nearest even number
            // this is the method used by System.Math.Round().
            return (integralPart.RawValue & ONE) == 0
                       ? integralPart
                       : integralPart + One;
        }

		/// <summary>
		/// Adds x and y. Performs saturating addition, i.e. in case of overflow, 
		/// rounds to MinValue or MaxValue depending on sign of operands.
		/// </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Fix64 operator +(Fix64 x, Fix64 y) {
#if CHECKMATH
			var xl = x.m_rawValue;
            var yl = y.m_rawValue;
            var sum = xl + yl;
            // if signs of operands are equal and signs of sum and x are different
            if (((~(xl ^ yl) & (xl ^ sum)) & MIN_VALUE) != 0) {
                sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
            }
            return new Fix64(sum);
#else
			return new Fix64(x.RawValue + y.RawValue);
#endif
		}

		public static Fix64 SafeAdd(Fix64 x, Fix64 y)
		{
			var xl = x.RawValue;
			var yl = y.RawValue;
			var sum = xl + yl;
			// if signs of operands are equal and signs of sum and x are different
			if (((~(xl ^ yl) & (xl ^ sum)) & MIN_VALUE) != 0)
			{
				sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
			}
			return new Fix64(sum);
		}

		/// <summary>
		/// Subtracts y from x. Performs saturating substraction, i.e. in case of overflow, 
		/// rounds to MinValue or MaxValue depending on sign of operands.
		/// </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Fix64 operator -(Fix64 x, Fix64 y) {
#if CHECKMATH
			var xl = x.m_rawValue;
            var yl = y.m_rawValue;
            var diff = xl - yl;
            // if signs of operands are different and signs of sum and x are different
            if ((((xl ^ yl) & (xl ^ diff)) & MIN_VALUE) != 0) {
                diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
            }
            return new Fix64(diff);
#else
			return new Fix64(x.RawValue - y.RawValue);
#endif
		}

		public static Fix64 SafeSub(Fix64 x, Fix64 y)
		{
			var xl = x.RawValue;
			var yl = y.RawValue;
			var diff = xl - yl;
			// if signs of operands are different and signs of sum and x are different
			if ((((xl ^ yl) & (xl ^ diff)) & MIN_VALUE) != 0)
			{
				diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
			}
			return new Fix64(diff);
		}

        static long AddOverflowHelper(long x, long y, ref bool overflow) {
            var sum = x + y;
            // x + y overflows if sign(x) ^ sign(y) != sign(sum)
            overflow |= ((x ^ y ^ sum) & MIN_VALUE) != 0;
            return sum;
        }

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Fix64 operator *(Fix64 x, Fix64 y) {
#if CHECKMATH
			var xl = x.m_rawValue;
            var yl = y.m_rawValue;

            var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
            var xhi = xl >> FRACTIONAL_PLACES;
            var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
            var yhi = yl >> FRACTIONAL_PLACES;

            var lolo = xlo * ylo;
            var lohi = (long)xlo * yhi;
            var hilo = xhi * (long)ylo;
            var hihi = xhi * yhi;

            var loResult = lolo >> FRACTIONAL_PLACES;
            var midResult1 = lohi;
            var midResult2 = hilo;
            var hiResult = hihi << FRACTIONAL_PLACES;

            bool overflow = false;
            var sum = AddOverflowHelper((long)loResult, midResult1, ref overflow);
            sum = AddOverflowHelper(sum, midResult2, ref overflow);
            sum = AddOverflowHelper(sum, hiResult, ref overflow);

            bool opSignsEqual = ((xl ^ yl) & MIN_VALUE) == 0;

            // if signs of operands are equal and sign of result is negative,
            // then multiplication overflowed positively
            // the reverse is also true
            if (opSignsEqual) {
                if (sum < 0 || (overflow && xl > 0)) {
					throw new OverflowException();
                    return MaxValue;
                }
            }
            else {
                if (sum > 0) {
					throw new OverflowException();
					return MinValue;
                }
            }

            // if the top 32 bits of hihi (unused in the result) are neither all 0s or 1s,
            // then this means the result overflowed.
            var topCarry = hihi >> FRACTIONAL_PLACES;
            if (topCarry != 0 && topCarry != -1 /*&& xl != -17 && yl != -17*/) {
				throw new OverflowException();
				return opSignsEqual ? MaxValue : MinValue; 
            }

            // If signs differ, both operands' magnitudes are greater than 1,
            // and the result is greater than the negative operand, then there was negative overflow.
            if (!opSignsEqual) {
                long posOp, negOp;
                if (xl > yl) {
                    posOp = xl;
                    negOp = yl;
                }
                else {
                    posOp = yl;
                    negOp = xl;
                }
                if (sum > negOp && negOp < -ONE && posOp > ONE) {
					throw new OverflowException();
					return MinValue;
                }
            }

            return new Fix64(sum);
#else
			var xl = x.RawValue;
			var yl = y.RawValue;

			var xlo = (ulong)(xl & FRACTIONAL_PLACES_VALUE);
			var xhi = xl >> FRACTIONAL_PLACES;
			var ylo = (ulong)(yl & FRACTIONAL_PLACES_VALUE);
			var yhi = yl >> FRACTIONAL_PLACES;

			var lolo = xlo * ylo;
			var lohi = (long)xlo * yhi;
			var hilo = xhi * (long)ylo;
			var hihi = xhi * yhi;

			var loResult = lolo >> FRACTIONAL_PLACES;
			var midResult1 = lohi;
			var midResult2 = hilo;
			var hiResult = hihi << FRACTIONAL_PLACES;

			var sum = (long)loResult + midResult1 + midResult2 + hiResult;
			return new Fix64(sum);
#endif
		}

		public static Fix64 SafeMul(Fix64 x, Fix64 y)
		{
			var xl = x.RawValue;
			var yl = y.RawValue;

			var xlo = (ulong)(xl & FRACTIONAL_PLACES_VALUE);
			var xhi = xl >> FRACTIONAL_PLACES;
			var ylo = (ulong)(yl & FRACTIONAL_PLACES_VALUE);
			var yhi = yl >> FRACTIONAL_PLACES;

			var lolo = xlo * ylo;
			var lohi = (long)xlo * yhi;
			var hilo = xhi * (long)ylo;
			var hihi = xhi * yhi;

			var loResult = lolo >> FRACTIONAL_PLACES;
			var midResult1 = lohi;
			var midResult2 = hilo;
			var hiResult = hihi << FRACTIONAL_PLACES;

			bool overflow = false;
			var sum = AddOverflowHelper((long)loResult, midResult1, ref overflow);
			sum = AddOverflowHelper(sum, midResult2, ref overflow);
			sum = AddOverflowHelper(sum, hiResult, ref overflow);

			bool opSignsEqual = ((xl ^ yl) & MIN_VALUE) == 0;

			// if signs of operands are equal and sign of result is negative,
			// then multiplication overflowed positively
			// the reverse is also true
			if (opSignsEqual)
			{
				if (sum < 0 || (overflow && xl > 0))
				{
					return MaxValue;
				}
			}
			else
			{
				if (sum > 0)
				{
					return MinValue;
				}
			}

			// if the top 32 bits of hihi (unused in the result) are neither all 0s or 1s,
			// then this means the result overflowed.
			var topCarry = hihi >> FRACTIONAL_PLACES;
			if (topCarry != 0 && topCarry != -1 /*&& xl != -17 && yl != -17*/)
			{
				return opSignsEqual ? MaxValue : MinValue;
			}

			// If signs differ, both operands' magnitudes are greater than 1,
			// and the result is greater than the negative operand, then there was negative overflow.
			if (!opSignsEqual)
			{
				long posOp, negOp;
				if (xl > yl)
				{
					posOp = xl;
					negOp = yl;
				}
				else
				{
					posOp = yl;
					negOp = xl;
				}
				if (sum > negOp && negOp < -ONE && posOp > ONE)
				{
					return MinValue;
				}
			}

			return new Fix64(sum);
		}

        [MethodImpl(MethodImplOptions.AggressiveInlining)] 
        static int CountLeadingZeroes(ulong x) {
            int result = 0;
            while ((x & 0xF000000000000000) == 0) { result += 4; x <<= 4; }
            while ((x & 0x8000000000000000) == 0) { result += 1; x <<= 1; }
            return result;
        }

        public static Fix64 operator /(Fix64 x, Fix64 y) {
            var xl = x.RawValue;
            var yl = y.RawValue;

            if (yl == 0) {
				return Fix64.MaxValue;
                //throw new DivideByZeroException();
            }

            var remainder = (ulong)(xl >= 0 ? xl : -xl);
            var divider = (ulong)(yl >= 0 ? yl : -yl);
            var quotient = 0UL;
            var bitPos = FRACTIONAL_PLACES + 1;


            // If the divider is divisible by 2^n, take advantage of it.
            while ((divider & 0xF) == 0 && bitPos >= 4) {
                divider >>= 4;
                bitPos -= 4;
            }

            while (remainder != 0 && bitPos >= 0) {
                int shift = CountLeadingZeroes(remainder);
                if (shift > bitPos) {
                    shift = bitPos;
                }
                remainder <<= shift;
                bitPos -= shift;

                var div = remainder / divider;
                remainder = remainder % divider;
                quotient += div << bitPos;

                // Detect overflow
                if ((div & ~(0xFFFFFFFFFFFFFFFF >> bitPos)) != 0) {
                    return ((xl ^ yl) & MIN_VALUE) == 0 ? MaxValue : MinValue;
                }

                remainder <<= 1;
                --bitPos;
            }

            // rounding
            ++quotient;
            var result = (long)(quotient >> 1);
            if (((xl ^ yl) & MIN_VALUE) != 0) {
                result = -result;
            }

            return new Fix64(result);
        }

        public static Fix64 operator %(Fix64 x, Fix64 y) {
            return new Fix64(
                x.RawValue == MIN_VALUE & y.RawValue == -1 ? 
                0 :
                x.RawValue % y.RawValue);
        }

        /// <summary>
        /// Performs modulo as fast as possible; throws if x == MinValue and y == -1.
        /// Use the operator (%) for a more reliable but slower modulo.
        /// </summary>
        public static Fix64 FastMod(Fix64 x, Fix64 y) {
            return new Fix64(x.RawValue % y.RawValue);
        }

        public static Fix64 operator -(Fix64 x) {
            return x.RawValue == MIN_VALUE ? MaxValue : new Fix64(-x.RawValue);
        }

        public static bool operator ==(Fix64 x, Fix64 y) {
            return x.RawValue == y.RawValue;
        }

        public static bool operator !=(Fix64 x, Fix64 y) {
            return x.RawValue != y.RawValue;
        }

        public static bool operator >(Fix64 x, Fix64 y) {
            return x.RawValue > y.RawValue;
        }

        public static bool operator <(Fix64 x, Fix64 y) {
            return x.RawValue < y.RawValue;
        }

        public static bool operator >=(Fix64 x, Fix64 y) {
            return x.RawValue >= y.RawValue;
        }

        public static bool operator <=(Fix64 x, Fix64 y) {
            return x.RawValue <= y.RawValue;
        }


        /// <summary>
        /// Returns the square root of a specified number.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        /// The argument was negative.
        /// </exception>
        public static Fix64 Sqrt(Fix64 x) {
            var xl = x.RawValue;
            if (xl < 0) {
                // We cannot represent infinities like Single and Double, and Sqrt is
                // mathematically undefined for x < 0. So we just throw an exception.
                throw new ArgumentOutOfRangeException("Negative value passed to Sqrt", "x");
            }

            var num = (ulong)xl;
            var result = 0UL;

            // second-to-top bit
            var bit = 1UL << (NUM_BITS - 2);

            while (bit > num) {
                bit >>= 2;
            }

            // The main part is executed twice, in order to avoid
            // using 128 bit values in computations.
            for (var i = 0; i < 2; ++i) {
                // First we get the top 48 bits of the answer.
                while (bit != 0) {
                    if (num >= result + bit) {
                        num -= result + bit;
                        result = (result >> 1) + bit;
                    }
                    else {
                        result = result >> 1;
                    }
                    bit >>= 2;
                }

                if (i == 0) {
                    // Then process it again to get the lowest 16 bits.
                    if (num > (1UL << FRACTIONAL_PLACES) - 1) {
                        // The remainder 'num' is too large to be shifted left
                        // by 32, so we have to add 1 to result manually and
                        // adjust 'num' accordingly.
                        // num = a - (result + 0.5)^2
                        //       = num + result^2 - (result + 0.5)^2
                        //       = num - result - 0.5
                        num -= result;
                        num = (num << FRACTIONAL_PLACES) - FRACTIONAL_PLACES_VALUE1;
                        result = (result << FRACTIONAL_PLACES) + FRACTIONAL_PLACES_VALUE1;
                    }
                    else {
                        num <<= FRACTIONAL_PLACES;
                        result <<= FRACTIONAL_PLACES;
                    }

                    bit = 1UL << (FRACTIONAL_PLACES - 2);
                }
            }
            // Finally, if next bit would have been 1, round the result upwards.
            if (num > result) {
                ++result;
            }
            return new Fix64((long)result);
        }

        /// <summary>
        /// Returns the Sine of x.
        /// This function has about 9 decimals of accuracy for small values of x.
        /// It may lose accuracy as the value of x grows.
        /// Performance: about 25% slower than Math.Sin() in x64, and 200% slower in x86.
        /// </summary>
        public static Fix64 Sin(Fix64 x) {
            bool flipHorizontal, flipVertical;
            var clampedL = ClampSinValue(x.RawValue, out flipHorizontal, out flipVertical);
            var clamped = new Fix64(clampedL);

            // Find the two closest values in the LUT and perform linear interpolation
            // This is what kills the performance of this function on x86 - x64 is fine though
            var rawIndex = clamped * LutInterval;
            var roundedIndex = Round(rawIndex); 
            var indexError = rawIndex - roundedIndex;

            var nearestValue = new Fix64(SinLut[flipHorizontal ? 
                SinLut.Length - 1 - (int)roundedIndex : 
                (int)roundedIndex]);
            var secondNearestValue = new Fix64(SinLut[flipHorizontal ? 
                SinLut.Length - 1 - (int)roundedIndex - SignI(indexError) : 
                (int)roundedIndex + SignI(indexError)]);

            var delta = (indexError * Abs(nearestValue - secondNearestValue)).RawValue;
            var interpolatedValue = nearestValue.RawValue + (flipHorizontal ? -delta : delta);
            var finalValue = flipVertical ? -interpolatedValue : interpolatedValue;
            return new Fix64(finalValue);
        }

        /// <summary>
        /// Returns a rough approximation of the Sine of x.
        /// This is at least 3 times faster than Sin() on x86 and slightly faster than Math.Sin(),
        /// however its accuracy is limited to 4-5 decimals, for small enough values of x.
        /// </summary>
        public static Fix64 FastSin(Fix64 x) {
            bool flipHorizontal, flipVertical;
            var clampedL = ClampSinValue(x.RawValue, out flipHorizontal, out flipVertical);

            // Here we use the fact that the SinLut table has a number of entries
            // equal to (PI_OVER_2 >> 15) to use the angle to index directly into it
            var rawIndex = (uint)(clampedL >> 15);
            if (rawIndex >= LUT_SIZE) {
                rawIndex = LUT_SIZE - 1;
            }
            var nearestValue = SinLut[flipHorizontal ?
                SinLut.Length - 1 - (int)rawIndex :
                (int)rawIndex];
            return new Fix64(flipVertical ? -nearestValue : nearestValue);
        }



        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] 
        static long ClampSinValue(long angle, out bool flipHorizontal, out bool flipVertical) {
            // Clamp value to 0 - 2*PI using modulo; this is very slow but there's no better way AFAIK
            var clamped2Pi = angle % PI_TIMES_2;
            if (angle < 0) {
                clamped2Pi += PI_TIMES_2;
            }

            // The LUT contains values for 0 - PiOver2; every other value must be obtained by
            // vertical or horizontal mirroring
            flipVertical = clamped2Pi >= PI;
            // obtain (angle % PI) from (angle % 2PI) - much faster than doing another modulo
            var clampedPi = clamped2Pi;
            while (clampedPi >= PI) {
                clampedPi -= PI;
            }
            flipHorizontal = clampedPi >= PI_OVER_2;
            // obtain (angle % PI_OVER_2) from (angle % PI) - much faster than doing another modulo
            var clampedPiOver2 = clampedPi;
            if (clampedPiOver2 >= PI_OVER_2) {
                clampedPiOver2 -= PI_OVER_2;
            }
            return clampedPiOver2;
        }

        /// <summary>
        /// Returns the cosine of x.
        /// See Sin() for more details.
        /// </summary>
        public static Fix64 Cos(Fix64 x) {
            var xl = x.RawValue;
            var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
            return Sin(new Fix64(rawAngle));
        }

        /// <summary>
        /// Returns a rough approximation of the cosine of x.
        /// See FastSin for more details.
        /// </summary>
        public static Fix64 FastCos(Fix64 x) {
            var xl = x.RawValue;
            var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
            return FastSin(new Fix64(rawAngle));
        }

        /// <summary>
        /// Returns the tangent of x.
        /// </summary>
        /// <remarks>
        /// This function is not well-tested. It may be wildly inaccurate.
        /// </remarks>
        public static Fix64 Tan(Fix64 x) {
            var clampedPi = x.RawValue % PI;
            var flip = false;
            if (clampedPi < 0) {
                clampedPi = -clampedPi;
                flip = true;
            }
            if (clampedPi > PI_OVER_2) {
                flip = !flip;
                clampedPi = PI_OVER_2 - (clampedPi - PI_OVER_2);
            }

            var clamped = new Fix64(clampedPi);

            // Find the two closest values in the LUT and perform linear interpolation
            var rawIndex = clamped * LutInterval;
            var roundedIndex = Round(rawIndex);
            var indexError = rawIndex - roundedIndex;

            var nearestValue = new Fix64(TanLut[(int)roundedIndex]);
            var secondNearestValue = new Fix64(TanLut[(int)roundedIndex + SignI(indexError)]);

            var delta = (indexError * Abs(nearestValue - secondNearestValue)).RawValue;
            var interpolatedValue = nearestValue.RawValue + delta;
            var finalValue = flip ? -interpolatedValue : interpolatedValue;
            return new Fix64(finalValue);
        }

        public static Fix64 FastAtan2(Fix64 y, Fix64 x) {
            var yl = y.RawValue;
            var xl = x.RawValue;
            if (xl == 0) {
                if (yl > 0) {
                    return PiOver2;
                }
                if (yl == 0) {
                    return Zero;
                }
                return -PiOver2;
            }
            Fix64 atan;
            var z = y / x;

			// Deal with overflow
			if (SafeAdd(One, SafeMul(SafeMul(C0p28, z), z)) == MaxValue) {
				return y.RawValue < 0 ? -PiOver2 : PiOver2;
            }

            if (Abs(z) < One) {
                atan = z / (One + C0p28 * z * z);
                if (xl < 0) {
                    if (yl < 0) {
                        return atan - Pi;
                    }
                    return atan + Pi;
                }
            }
            else {
                atan = PiOver2 - z / (z * z + C0p28);
                if (yl < 0) {
                    return atan - Pi;
                }
            }
            return atan;
        }

		/// <summary>
		/// Returns the arctan of of the specified number, calculated using Euler series
		/// </summary>
		public static Fix64 Atan(Fix64 z)
		{
			if (z.RawValue == 0)
				return Zero;

			// Force positive values for argument
			// Atan(-z) = -Atan(z).
			bool neg = (z.RawValue < 0);
			if (neg) z = -z;

			Fix64 result;

			if (z == One)
				result = PiOver4;
			else
			{
				bool invert = z > One;
				if (invert) z = One / z;
				
				result = One;
				Fix64 term = One;
				
				Fix64 zSq = z * z;
				Fix64 zSq2 = zSq * Two;
				Fix64 zSqPlusOne = zSq + One;
				Fix64 zSq12 = zSqPlusOne * Two;
				Fix64 dividend = zSq2;
				Fix64 divisor = zSqPlusOne * Three;

				for (int i = 2; i < 30; i++)
				{
					term *= dividend / divisor;
					result += term;

					dividend += zSq2;
					divisor += zSq12;

					if (term.RawValue == 0)
						break;
				}

				result = result * z / zSqPlusOne;

				if (invert)
					result = PiOver2 - result;
			}

			if (neg) result = -result;
			return result;
		}

		public static Fix64 Atan2(Fix64 y, Fix64 x)
		{
			var yl = y.RawValue;
			var xl = x.RawValue;
			if (xl == 0)
			{
				if (yl > 0)
					return PiOver2;
				if (yl == 0)
					return Zero;
				return -PiOver2;
			}

			var z = y / x;

			// Deal with overflow
			if (SafeAdd(One, SafeMul(SafeMul((Fix64)0.28M, z), z)) == MaxValue)
			{
				return y.RawValue < 0 ? -PiOver2 : PiOver2;
			}
			Fix64 atan = Atan(z);

			if (xl < 0)
			{
				if (yl < 0)
					return atan - Pi;
				return atan + Pi;
			}

			return atan;
		}

		public static implicit operator Fix64(int value)
		{
			return new Fix64(value);
		}
		public static explicit operator Fix64(long value) {
            return new Fix64(value * ONE);
        }
        public static explicit operator long(Fix64 value) {
            return value.RawValue >> FRACTIONAL_PLACES;
        }
        public static explicit operator Fix64(float value) {
            return new Fix64((long)(value * ONE));
        }
        public static explicit operator float(Fix64 value) {
            return (float)value.RawValue / ONE;
        }
        public static explicit operator Fix64(double value) {
            return new Fix64((long)(value * ONE));
        }
        public static explicit operator double(Fix64 value) {
            return (double)value.RawValue / ONE;
        }
        public static implicit operator Fix64(decimal value) {
            return new Fix64((long)(value * ONE));
        }
        public static explicit operator decimal(Fix64 value) {
            return (decimal)value.RawValue / ONE;
        }

        public override bool Equals(object obj) {
            return obj is Fix64 && ((Fix64)obj).RawValue == RawValue;
        }

        public override int GetHashCode() {
            return RawValue.GetHashCode();
        }

        public bool Equals(Fix64 other) {
            return RawValue == other.RawValue;
        }

        public int CompareTo(Fix64 other) {
            return RawValue.CompareTo(other.RawValue);
        }

        public override string ToString() {
            return ((decimal)this).ToString();
        }

        public static Fix64 FromRaw(long rawValue) {
            return new Fix64(rawValue);
        }

        /// <summary>
        /// This is the constructor from raw value; it can only be used interally.
        /// </summary>
        /// <param name="rawValue"></param>
        Fix64(long rawValue) {
            RawValue = rawValue;
        }

        public Fix64(int value) {
            RawValue = value * ONE;
        }
        
        public Fix64(float value)
        {
	        RawValue = (long)(value * ONE);
        }
    }
}

GitHub: https://github.com/asik/FixedMath.Net.git

VFactor定点数

https://github.com/Prince-Ling/LogicPhysics/tree/master

This post is licensed under CC BY 4.0 by the author.