SymPy: How to return an expression in terms of other [removed]s)?

前端 未结 3 1471
無奈伤痛
無奈伤痛 2021-01-03 05:40

I\'m fairly new to SymPy and have what might be a basic question. Or I might simply be misinterpreting how SymPy is supposed to be used.

Is there a way to create an

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 06:18

    Checking the source for sympy.physics.units you can see that all units are defined in terms of meters, kilograms, seconds, amperes, kelvins, moles and candelas. These are the base units.

    Then a mile is defined as 5280 feet, and a foot is defined as 0.3048 meters.

    So all expressions using non-base units will have the non-base units replaced with the base units.

    You can define your own units which you can subsitute into an expression when you need an expression to use particular units:

    import sympy.physics.units as units
    from sympy import Rational
    
    my_mile = units.Unit('my_mile', 'mile')
    my_hour = units.Unit('my_hour', 'hour')
    

    Then define a dictionary which will substitute the base units for your new units.

    converter = {units.m: my_mile/Rational('1609.344'),
                 units.s: my_hour/Rational('3600')}
    

    Perform all your calculations using the base units. Then if you want a value using miles and hours, you can substitute your new units into the expression.

    v = 10*units.miles/units.hour
    print v # = 2794*m/(625*s)
    
    print v.subs(converter) # = 10*mile/hour
    

    Use ars answer for getting the docs. Sympy's repository is here: https://github.com/sympy/sympy

    There is a README file in the docs folder which describes how to create html docs.

提交回复
热议问题