Extending Python's Number hierarchy

28,683
16
Published 2023-01-30
Try Brilliant: brilliant.org/mCoding/

Complex rational numbers.

Say you wanted to implement your own custom number type in Python, how would you do it? In this video, we'll take a look at a custom implementation of an infinite precision number type for complex numbers with rational components, aka "Gaussian rationals".

― mCoding with James Murphy (mcoding.io/)

Source code: github.com/mCodingLLC/VideosSampleCode
Slots video:    • Python __slots__ and object layout ex...  
Fast pow video:    • Fast pow! A general recursive power a...  
New vs init video:    • __new__ vs __init__ in Python  
Python numbers docs: docs.python.org/3/library/numbers.html
Python stdtypes docs: docs.python.org/3/library/stdtypes.html

SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
patreon.com/mCoding

Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJ…

Want to donate crypto? Check out the rest of my supported donations on my website!
mcoding.io/donate

Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, Mark M, Mutual Information

BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: discord.gg/Ye9yJtZQuN
Github: github.com/mCodingLLC/
Reddit: www.reddit.com/r/mCoding/
Facebook: www.facebook.com/james.mcoding

CHAPTERS
---------------------------------------------------
0:00 Intro
1:21 Start of implementation
4:00 Arithmetic operations
11:32 Hash and equality
15:13 Thanks to Brillian

All Comments (21)
  • I feel like I could hack together something like that in half an hour or so, but you pointed out so many pitfalls that I would 100% have fallen into. The subtle logic of reverse ordered addition and fallback operators would never even have crossed my mind. Not to mention all the complexities to do with hash...
  • I really like this code example. Many languages have theoretical support for additional number types via operator overloads and custom classes, but to see how much Python gives you to hook into is wonderful!
  • @kevinryan2992
    This is an awesome example of something I struggle with pretty often in python. It can be easy to write any given class, but writing well behaved classes that interact "correctly" with the rest of the python ecosystem is an art form.
  • It would be a great follow-up video to walk thru and discuss the testing of this class
  • @AJMansfield1
    I've definitely fallen into some of these pitfalls before when I tried to implement modulo integer and other finite field types.
  • In the Gaussian integers, certain integers you would consider “prime” can be factored, e.g. >>> (10 - 1j) * (10 + 1j) == 101 True
  • @dougmercer
    Nice video! It's surprising how tricky these simple classes turn out to be... I did a video on my channel reimplementing range() from scratch, and it was a nightmare to get the details right!
  • @Zifox20
    Really useful video to have a concrete example of all these functions, thank you so much!
  • @anjaan480
    Love your lectures, always something new to learn. Would be happy if you did some lectures on third party libraries like celery too.
  • 3:48 If you define a ‗‗getitem‗‗ method, that is sufficient to allow your type to be implicitly converted to a tuple where the context requires it.
  • Impressive video and content. Infinite precision too! I've repurposed complex class for points. point.real = x, point.imag = y and abs of the complex number finds the distance of the point from the origin.
  • Could you suggest a reading list or books to master C++ and Python. Also is there a way I could ask you to mentor me to be a better programmer. I watched your old noob coding pitfalls in C++. I am just amazed there is so much to learn from you !
  • @lior_haddad
    Correct me if I'm wrong, but in CPython, the -1 => -2 substitution is automatically done if you return -1 from __hash__, no?
  • @DonAlcohol
    on the same topic: i find it verry unfortunate that in pytthon both parts of a complex number are by default floats and not ints in the case of just 1+1j ,and while floats get printed as 0.0 by default the floats in the real and imag parts of a complex dont mirror this behavior in the case of round numbers... some this leads to some weird behavior (possibly because of this -> numbers being floats that is) that is less so but better in v2.7, while being completely bonkers in any 3.+ as far as i know. try enering these and see what the results are: (especially try figuring out why the sign of a nonspecified realpart takes the sign of the imag part and why the sign flips in the +example given the behavior just described: as a int referenc: `0`result`0` and `-0`result`0` 1: `0-0j`result:`0j` 2: `-0j` result:`(-0-0j)` 3: `(-0-0j)`result:`0j` 4 `-1j` result:`(-0-1j)` 5: `1-0j`result`(1+0j)`
  • oh that was a very nice lecture. Just wondering why you checked types with "type(x) == Class" instead of using the isinstance() built in?
  • @dmytruek
    Isn't `sqrt` function from `math` library faster than `** .5`? If yes, why you didn't use it?
  • @lunalect
    I know the point is to learn the internals of Python (and thus not to rely on an external library) but would the plum package be helpful here in terms of dispatching on the right types?
  • @pamdemonia
    Very interesting, although I now am both better prepared to create a numerical class and also more daunted by the whole idea!