【问题标题】:How do I deal with C# decimals when using IronPython?使用 IronPython 时如何处理 C# 小数?
【发布时间】:2015-08-03 14:55:15
【问题描述】:

总的来说,我是 IronPython 和 Python 的新手。我正在尝试使用 C# 小数和 IronPython 数学函数。当我尝试返回参数的绝对值时,当参数为小数时会出现类型异常。这是我的代码:

    [TestMethod]
    public void CallDecimal()
    {
        var pySrc =
@"def MyAbs(arg):
    return abs(arg)";

        // host python and execute script
        var engine = IronPython.Hosting.Python.CreateEngine();
        var scope = engine.CreateScope();
        engine.Execute(pySrc, scope);

        // get function with a strongly typed signature
        var myAbs = scope.GetVariable<Func<decimal, decimal>>("MyAbs");

        Assert.AreEqual(5m, myAbs(-5m));
    }

我收到的错误消息是:

IronPython.Runtime.Exceptions.TypeErrorException: bad operand type for abs(): 'Decimal'

有没有接受小数的 Python 绝对值函数?如果没有,写一个容易吗?如果我可以指定函数参数的类型,我会尝试像这样创建自己的 abs 函数:

define abs(Decimal arg):
    return arg < 0 ? -arg : arg

【问题讨论】:

  • 您可以编写一个类似于您给出的示例的简单函数。 def my_abs(arg): return arg if arg &gt; 0 else -arg
  • @AnthonyHilyard 成功了!谢谢。只是好奇,有没有办法用小数调用内置的 abs ?或者是否有一些适用于 C# 小数的十进制数学库? abs 很容易实现,但atan 不是
  • 您可能需要查看dmath。它为小数提供了 atan 函数,以及许多其他函数。

标签: c# python decimal ironpython


【解决方案1】:

您始终可以选择导入 .NET Math 类并使用其中的方法。

var pySrc =
@"def MyAbs(arg):
    from System import Math
    return Math.Abs(arg)";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多