plus/minus operator for python ±

前端 未结 7 591
遇见更好的自我
遇见更好的自我 2020-12-31 02:20

I am looking for a way to do a plus/minus operation in python 2 or 3. I do not know the command or operator, and I cannot find a command or operator to do this.

Am I

相关标签:
7条回答
  • 2020-12-31 02:41

    If you are looking to print the ± symbol, just use:

    print(u"\u00B1")
    
    0 讨论(0)
  • 2020-12-31 02:57

    Another possibility: uncertainties is a module for doing calculations with error tolerances, ie

    (2.1 +/- 0.05) + (0.6 +/- 0.05)    # => (2.7 +/- 0.1)
    

    which would be written as

    from uncertainties import ufloat
    
    ufloat(2.1, 0.05) + ufloat(0.6, 0.05)
    

    Edit: I was getting some odd results, and after a bit more playing with this I figured out why: the specified error is not a tolerance (hard additive limits as in engineering blueprints) but a standard-deviation value - which is why the above calculation results in

    ufloat(2.7, 0.07071)    # not 0.1 as I expected!
    
    0 讨论(0)
  • 2020-12-31 02:59

    If you happen to be using matplotlib, you can print mathematical expressions similar as one would with Latex. For the +/- symbol, you would use:

    print( r"value $\pm$ error" )
    

    Where the r converts the string to a raw format and the $-signs are around the part of the string that is a mathematical equation. Any words that are in this part will be in a different font and will have no whitespace between them unless explicitly noted with the correct code. This can be found on the relavent page of the matplotlib documentation.

    Sorry if this is too niche, but I stumbeled across this question trying to find this very answer.

    0 讨论(0)
  • 2020-12-31 03:03

    Instead of computing expressions like

    s1 = sqrt((125.0 + 10.0*sqrt(19)) / 366.0)
    s2 = sqrt((125.0 - 10.0*sqrt(19)) / 366.0)
    

    you could use

    pm = numpy.array([+1, -1])
    s1, s2 = sqrt((125.0 + pm * 10.0*sqrt(19)) / 366.0)
    
    0 讨论(0)
  • 2020-12-31 03:05

    I think you want that for an equation like this;

    enter image description here

    Well there is no operator for that unless you don't use SymPy, only you can do is make an if statement and find each multiplier.

    0 讨论(0)
  • 2020-12-31 03:07

    There is no such object in SymPy yet (as you saw, there is an issue suggesting one https://github.com/sympy/sympy/issues/5305). It's not hard to emulate, though. Just create a Symbol, and swap it out with +1 and -1 separately at the end. Like

    pm = Symbol(u'±') # The u is not needed in Python 3. I used ± just for pretty printing purposes. It has no special meaning.
    expr = 1 + pm*x # Or whatever
    # Do some stuff
    exprpos = expr.subs(pm, 1)
    exprneg = expr.subs(pm, -1)
    

    You could also just keep track of two equations from the start.

    0 讨论(0)
提交回复
热议问题