1

I'm new to IronPython and Python in general. I'm trying to work with C# decimals and IronPython math functions. When I try to return the absolute value of an argument, I get a type exception when the argument is a decimal. Here's my code:

    [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));
    }

The error message I get says:

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

Is there a Python absolute value function that accepts decimals? If not, is it easy to write one? If I could specify the types of function parameters, I'd try to create my own abs function like this:

define abs(Decimal arg):
    return arg < 0 ? -arg : arg
user2023861
  • 8,030
  • 9
  • 57
  • 86
  • 1
    You could write a simple function similar to the example you have given. `def my_abs(arg): return arg if arg > 0 else -arg` – Anthony Hilyard Jul 27 '15 at 16:07
  • @AnthonyHilyard that worked! Thanks. Just curious, is there a way to call the built-in abs with a decimal? Or is there some decimal math library that works with C# decimals? `abs` is easy to implement, but `atan` isn't – user2023861 Jul 27 '15 at 16:15
  • You may want to look into [dmath](https://code.google.com/p/dmath/). It provides the atan function for decimals, along with many other functions. – Anthony Hilyard Jul 27 '15 at 16:51

1 Answers1

2

You always have the option to import the .NET Math class and use the methods there.

var pySrc =
@"def MyAbs(arg):
    from System import Math
    return Math.Abs(arg)";
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272