|
1 | | -using System; |
| 1 | +using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.Drawing; |
4 | 4 | using System.IO; |
@@ -1016,6 +1016,36 @@ public async Task IssueByMartinDevans() |
1016 | 1016 | Assert.AreEqual(a, x.split(new[] { 3, 5, 6, 10 }).repr()); |
1017 | 1017 | } |
1018 | 1018 |
|
| 1019 | + |
| 1020 | + [TestMethod] |
| 1021 | + public async Task F16Workaround() |
| 1022 | + { |
| 1023 | + // use byte array to create float16 array |
| 1024 | + |
| 1025 | + // numbers in float16: |
| 1026 | + // 0 01111 0000000000 = 2^0 * (1 + 0/1024) = 1 |
| 1027 | + // 1 01111 0000000000 = -1 * 2 ^ 0 * (1 + 0 / 1024) = -1 |
| 1028 | + // 0 11110 1111111111 = -1^(0) * 2^(15) * (1 + 1023/1024) ≈ 65504 |
| 1029 | + // see: https://devblogs.microsoft.com/dotnet/introducing-the-half-type/ |
| 1030 | + |
| 1031 | + // these bytes in binary notation correspond to f16 numbers 1, -1 and 65504 (float16 max value) |
| 1032 | + // note, the bytes are in reversed order to the bits shown above |
| 1033 | + var bytes = new byte[] { |
| 1034 | + 0b00000000, 0b00111100, // 1 |
| 1035 | + 0b00000000, 0b10111100, // -1 |
| 1036 | + 0b11111111, 0b01111011, // 65504 |
| 1037 | + }; |
| 1038 | + var floats = np.zeros(new Shape(3), np.float16); |
| 1039 | + Console.WriteLine(floats.repr); |
| 1040 | + // note, the using prevents a mem-leak with ctypes |
| 1041 | + using (var ctypes = floats.PyObject.ctypes) { |
| 1042 | + long ptr = ctypes.data; |
| 1043 | + Marshal.Copy(bytes, 0, new IntPtr(ptr), bytes.Length); |
| 1044 | + } |
| 1045 | + Console.WriteLine(floats.repr); |
| 1046 | + Assert.AreEqual("array([ 1.00e+00, -1.00e+00, 6.55e+04], dtype=float16)", floats.repr); |
| 1047 | + } |
| 1048 | + |
1019 | 1049 | // TODO: https://docs.scipy.org/doc/numpy/user/basics.indexing.html?highlight=slice#structural-indexing-tools |
1020 | 1050 | // TODO: https://docs.scipy.org/doc/numpy/user/basics.indexing.html?highlight=slice#assigning-values-to-indexed-arrays |
1021 | 1051 | // TODO: https://docs.scipy.org/doc/numpy/user/basics.indexing.html?highlight=slice#dealing-with-variable-numbers-of-indices-within-programs |
|
0 commit comments