Search code examples
python-3.xphysicsscientific-notation

How to calculate and store the number in scientific notation?


I am using Python to model the statistical physical, so I will deal with small numbers.

For example,

a = 2.22e-300, b = 3e-200

and I want to calculate

a * b = 6.66e-500.

However, in Python 3 it shows 0.0.

I am thinking to design a data type: the first part to store the float number, which is 6.66 here, and the second part stores the magnitude, which is -500.

May I ask how I can implement this? Or is there any better way to deal with the scientific number?


Solution

  • Create a class:

    class Sci_note:
        def __init__(self, base, exp):
            self.base = base
            self.exp = exp
        def __mul__(self, other):
            return Sci_note(self.base * other.base,
                            self.exp + other.exp)
        def __str__(self):
            return str(self.base) + 'e' + str(self.exp)
    

    and it functions as you would expect:

    >>> a = Sci_note(2.22, -300)
    >>> b = Sci_note(3, -200)
    >>> c = a * b
    >>> c.base
    6.66
    >>> c.exp
    -500
    

    update

    I added a __str__ method (above), so they are displayed properly when printed:

    >>> print(a)
    2.22e-300
    

    Of course, I have only implemented the multiplication method here, but I will leave it up to you to implement the others when required. It may be the case that you only need multiplication so I would be wasting everyone's time if I wrote them now!

    In addition, creating a __float__ handler would also not be useful here, as Python can't handle floats of the order ^-300, so it would be useless to return them as we would just get 0!