-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathpy.cs
More file actions
62 lines (55 loc) · 2.21 KB
/
Copy pathpy.cs
File metadata and controls
62 lines (55 loc) · 2.21 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
using System;
using System.Numerics;
using System.Text.RegularExpressions;
namespace NumSharp.Utilities
{
/// <summary>
/// Implements Python utility functions that are often used in connection with numpy
/// </summary>
public static class py
{
public static int[] range(int n)
{
var a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
return a;
}
/// <summary>
/// 解析单个Python风格的复数字符串为Complex对象
/// </summary>
private static readonly Regex _pythonComplexRegex = new Regex(
@"^(?<real>-?\d+(\.\d+)?)?((?<imagSign>\+|-)?(?<imag>\d+(\.\d+)?)?)?j$|^(?<onlyReal>-?\d+(\.\d+)?)$",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
public static Complex complex(string input)
{
var match = _pythonComplexRegex.Match(input);
if (!match.Success)
throw new FormatException($"Invalid Python complex format: '{input}'. Expected format like '10+5j', '3-2j', '4j' or '5'.");
// 解析仅实部的场景
if (match.Groups["onlyReal"].Success)
{
double real = double.Parse(match.Groups["onlyReal"].Value);
return new Complex(real, 0);
}
// 解析实部(默认0)
double realPart = 0;
if (double.TryParse(match.Groups["real"].Value, out double r))
realPart = r;
// 解析虚部(处理特殊情况:j / -j / +j)
double imagPart = 0;
string imagStr = match.Groups["imag"].Value;
string imagSign = match.Groups["imagSign"].Value;
if (string.IsNullOrEmpty(imagStr) && !string.IsNullOrEmpty(input.TrimEnd('j', 'J')))
{
// 处理仅虚部的情况:j → 1j, -j → -1j, +j → 1j
imagStr = "1";
}
if (double.TryParse(imagStr, out double im))
{
imagPart = im * (imagSign == "-" ? -1 : 1);
}
return new Complex(realPart, imagPart);
}
}
}