Can we have float -> binanry as fbin and binary -> float as fnum conversion in math library?

Can we have float → binary as fbin and binary → float as fnum conversion in math library?

I am not a professional programmer,
so my code is just a raw example.

# float -> binary and binary -> float conversion
from fractions import Fraction

def fbin(x):
    a, b = int(x), Fraction(str(x)) - int(x)
    result = list()
    result.append(bin(a)[2:])
    if not b:
        result.append("0")
        return result
    bits = ''
    for _ in range(50):
        b *= 2
        if b >= 1:
            bits += "1"
            b -= 1
        else:
            bits += "0"
    result.append(bits)
    return result

def fnum(number):
    q = int(number[0], 2)
    r = sum([int(bit) * (2 ** -(idx + 1))
             for idx, bit in enumerate((number[1]))])
    return q + r
>>> fbin(1113.3)
['10001011001', '01001100110011001100110011001100110011001100110011']
>>> fnum(_)
1113.3
>>> fbin(1e+2)
['1100100', '0']
>>> fnum(_)
100.0

We can convert a float to hex with a method:

>>> 1113.3.hex()
'0x1.1653333333333p+10'
>>> (1e+2).hex()
'0x1.9000000000000p+6'

and you could convert from there into binary if you wish.

Yes, i found that also.
So, I’ve tried to make exponentiation in different bases, using float to binary conversion first.

So, that is my playground. I realized that there is no a simple float to binary conversion method.

That is what motivated me to ask for this feature: float to binary and binary to float conversion.

from fractions import Fraction

def fbin(x):
    a, b = int(x), Fraction(str(x)) - int(x)
    result = list()
    result.append(bin(a)[2:])
    if not b:
        result.append("0")
        return result
    bits = ''
    for _ in range(50):
        b *= 2
        if b >= 1:
            bits += "1"
            b -= 1
        else:
            bits += "0"
    result.append(bits)
    return result

def fnum(number):
    q = int(number[0], 2)
    r = sum([int(bit) * (2 ** -(idx + 1))
             for idx, bit in enumerate((number[1]))])
    return q + r

def root(x, k, tolerance = 1e-15):
    a = m = 2.0
    while abs(m) > tolerance:
        m = (a ** k - x) / (k * a ** (k-1))
        a -= m
    return a

def exp(base, x):
    if x < 0: return 1 / exp(base, -x)
    exponent = fbin(x)

    q = 1
    for idx, bit in enumerate(exponent[0][::-1]):
        q *= base ** (int(bit) * (2 ** idx))

    r = 1
    for bit in exponent[1]:
        base = root(base, 2)
        r *= base ** (int(bit))

    return q * r

def nexp(x, tolerance = 1e-15):
    if x < 0: return 1 / nexp(-x)
    prod = a = i = 1
    while abs(prod) > tolerance:
        prod *= x / i
        a += prod
        i += 1
    return a

def ln(x, tolerance = 1e-15):
    a = m = 1.0
    while abs(m) > tolerance:
        t = nexp(a)
        m = 2 * (t - x) / (t + x)
        a -= m
    return a

def log(base, x, tolerance = 1e-15):
    a = m = 2.0
    scale = 2 / ln(base)
    while abs(m) > tolerance:
        t = exp(base, a)
        m = scale * (t - x) / (t + x)
        a -= m
    return a

if __name__ == "__main__":
    pass
>>> fbin(1113.3)
['10001011001', '01001100110011001100110011001100110011001100110011']
>>> fnum(_)
1113.3
>>> exp(2, 10)
1024.0
>>> log(2, 2 ** 10)
9.999999999999993

Hmm, if you’re going to express pi as an infinite series of rational numbers, there are far more logical ones to use than its binary expansion. Also, you’re not really going to get anywhere much by starting with a floating point representation (with only 53 bits to work with). But in any case, the main value of what you’re doing here IS the writing of the code; you’re learning by creating this. Also, I think you’re perhaps seeing exactly how poor Gemini can be as a learning tool.

So, I am using Python to test some of mine ideas.

me@amadeus:~$ python3 -q # 🐍
>>> def sin(x):
...     prod = a = 1
...     for i in range(1, 30):
...             prod *= x / i
...             if not i & 1: continue
...             prod *= -1
...             a += prod
...     return 1 - a
... 
>>> x = 0
>>> for _ in range(3):
...     x += sin(3 + x)
... 
>>> x
0.14159265358979323 ❤️‍🔥
>>> 
me@amadeus:~$

I am not a professional programmer,
I am just playing around, because I am curious to see,
how code is made?

me@amadeus:~$ python3 -q # 🐍
>>> def exp(x):
...     prod = a = 1
...     for i in range(1, 30):
...             prod *= x / i
...             a += prod
...     return a
... 
>>> def ln(x):
...     a = 0
...     for _ in range(1, 30):
...             a -= 1 - x / exp(a)
...     return a
... 
>>> def sin(x):
...     prod = a = 1
...     for i in range(1, 30):
...             prod *= x / i
...             if not i & 1: continue
...             prod *= -1
...             a += prod
...     return 1 - a
... 
>>> x = 3
>>> for _ in range(3):
...     x += sin(x)
... 
>>> x
3.141592653589793
>>> 
>>> exp(1/x * ln(x))
1.4396194958475905
>>> x ** (1/x)
1.4396194958475907
>>> 
>>> exp(x * ln(x))
36.46215960720795
>>> x ** x
36.4621596072079
>>> 
>>> exp(1/3 * ln(2))
1.2599210498948732
>>> 2 ** (1/3)
1.2599210498948732
>>> 
me@amadeus:~$

So, the next what I’ve tried, is to use exponentiation trough different base conversion,
therefore the one of method needed float to binary and binary to float conversion.

So, that is what motivated me to ask for this feature request:
binary to float and float to binary conversion.

I did also exponentiation using decimal base:

def root(x, k, tolerance = 1e-15):
    a = m = 2.0
    while abs(m) > tolerance:
        m = (a ** k - x) / (k * a ** (k-1))
        a -= m
    return a

def exp(base, x):
    a, b = int(x), x - int(x)
    result = base ** a
    for i in f'{b:.15f}'.split(".")[1]:
        base = root(base, 10)
        result *= base ** int(i)
    return result
from math import pi as π

print(root(27, 3))
print(log(2, 8))
print(exp(2, log(2, 10)))

print(exp(π, 1/π))
print(π ** (1/π))

print(exp(π, π))
print(π ** π)

print(log(2, 2 ** 10))
print(exp(2, 10))

/home/me/Pycharm/WelcomeScreen/.venv/bin/python script.py 
3.0
3.0
10.0
1.439619495847591
1.4396194958475907
36.46215960720791
36.4621596072079
10.0
1024.0

Process finished with exit code 0

The very best way to see how code is made is to make code :slight_smile: Figure out what you need, and then write it! This is far better than having specific tools handed to you.

Yes, I am agree. But we have just binary conversion just for integers.
Why not to have binary to float and float to binary conversion too? :upside_down_face:

Python aims to be “batteries included,” and for learning, experimentation, and teaching numerical computing, having a clean, built-in bridge between binary strings and floats would save a lot of reinventing the wheel!

So, maybe is better just to upgrade bin(x) to support floats to binary as well?
Therefore, we could upgrade float(x) to support binary to float as well?

I think, (1113.3).bin() / float.frombin('0b111.010101') should be ok.

def fbin(x):
    a, b = int(x), Fraction(str(x)) - int(x)
    result = list()
    result.append(bin(a)[2:])
    if not b:
        result.append("0")
        return result
    bits = ''
    for _ in range(50):
        b *= 2
        if b >= 1:
            bits += "1"
            b -= 1
        else:
            bits += "0"
    result.append(bits)
    return result

Hmm, this will not pass round-trip, the conversion is lossy. For example:

>>> x=1.1; n = fbin(x); assert x == fnum(n)
Traceback (most recent call last):
  File "<python-input-51>", line 1, in <module>
    x=1.1; n = fbin(x); assert x == fnum(n)
                               ^^^^^^^^^^^^
AssertionError

I guess what you actually want here is something like:

def fbin3(x):
    i = int(x)
    f = Fraction(x) - i
    return f'{i:b}', f'{f.numerator*(2**53//f.denominator):053b}'

Remember, that IEEE doubles (used to represent float’s in Python) have 53-bit mantissa. (Or you should change 50->54 in your code.)

Alternative variant (no Fraction’s):

fbin = lambda x: (f'{int(x):b}', f'{int((x - int(x))*2**53):053b}')

So, it’s essentially one-liner. Why we would like to have this in the stdlib?

So, my code is not the solution.
My first intention of my post was “an idea”, but it was put on “Python help”.

For a professional Python developer, there is no problem to build himself the conversion.

The problem is that a simple Python user, should reinvent the wheel.
We already have integer to binary conversion,
why not to have float to binary and binary to float?

I think, (1113.3).bin() / float.frombin('0b111.010101') should be ok.

Yes, Your version is absolutely exact! :upside_down_face:

PyDev console: starting.
Python 3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0] on linux
>>> from Aa import fbin, fnum
>>> fbinL = lambda x: (f'{int(x):b}', f'{int((x - int(x))*2**53):053b}')
>>> fbin(1113.3)
['10001011001', '01001100110011001100110011001100110011001100110011']
>>> fbinL(1113.3)
('10001011001', '01001100110011001100110011001100110011001100000000000')
>>> fnum(fbin(1113.3))
1113.3
>>> fnum(fbinL(1113.3))
1113.3
>>> fnum(fbin(1.1))
1.0999999999999996
>>> fnum(fbinL(1.1))
1.1

(I don’t think I’m a professional Python developer.)

But why we want to have it?

hex() / fromhex() methods were already suggested for you above. Those methods essentially works with floats in binary, just mantissa bits expressed by hexadecimal digits (i.e. as 4-groups of bits). Basically, it’s just a more compact notation.

Note that many languages have support for hexadecimal floating-point literals (e.g. C), but almost none — for binary floating-point literals (maybe Julia?).

It was suggested before to add more tight support for such floating-point representations in Python, maybe as literals or string formatting types. But that idea has no support from core developers. See this thread or this PEP draft.

You might want to use more specialized packages, like gmpy2 or mpmath. Both have support for hexadecimal and binary representations of floating-point types. The mpmath REPL even has support for hexadecimal/binary literals per default, e.g.:

$ python -m mpmath
>>> 1.1  # float literals are transformed to mpmath real type, mpf
1.1000000000000001
>>> type(_)
<class 'mpmath.ctx_mp_python.mpf'>
>>> 1j  # complex literals - to mpc
(0.0 + 1.0j)
>>> type(_)
<class 'mpmath.ctx_mp_python.mpc'>
>>> 0b1.10101111101p0  # though, exponent is mandatory, like in C
1.68603515625
>>> type(_)
<class 'mpmath.ctx_mp_python.mpf'>
>>> 0x1.123p-4
0.0669403076171875
>>> type(_)
<class 'mpmath.ctx_mp_python.mpf'>
>>> f"{1.23:b}"  # format in binary
'1.001110101110000101000111101011100001010001111010111p+0'
>>> f"{1.23:a}"  # hexadecimal
'0x1.3ae147ae147aep+0'

Well, for real proposal (suitable for Ideas section) you have to do something more:

  1. provide full specification for above methods
  2. provide arguments why your proposal would be beneficial for many Python users.

See more on Changing Python.

Yes, You are a PROFESSIONAL Python developer: :innocent:

I am not, and never will be. My code tell about me, who am I. :upside_down_face:

Thank You for sharing the PEP draft and thread.
I see the battle You had to implement some new goodies useful for us, simple users,
that make our lives much pleasant. :deciduous_tree:

me@amadeus:~$ python3 -m mpmath
/usr/bin/python3: No module named mpmath
me@amadeus:~$ mkdir Tutor
me@amadeus:~$ cd Tutor/
me@amadeus:~/Tutor$ python3 -m venv agi
me@amadeus:~/Tutor$ source agi/bin/activate
(agi) me@amadeus:~/Tutor$ pip install --upgrade mpmath
Collecting mpmath
  Downloading mpmath-1.4.1-py3-none-any.whl.metadata (9.1 kB)
Downloading mpmath-1.4.1-py3-none-any.whl (567 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 567.8/567.8 kB 3.2 MB/s eta 0:00:00
Installing collected packages: mpmath
Successfully installed mpmath-1.4.1
(agi) me@amadeus:~/Tutor$ python -m mpmath
>>> f'{1113.3:b}'
'1.0001011001010011001100110011001100110011001100110011p+10'
>>> 
(agi) me@amadeus:~/Tutor$ deactivate 
me@amadeus:~/Tutor$ 

Hi, welcome to the group.

If you ask for a change to Python , other members are going to help, but also ask why? It takes effort to add features and you have a calculation, but does the community need it enough to add its support in core Python? Have you seen others needing that exact capability?

Python floats have a particular representation, how they are packed into a 64 bit location, and has means to dump (and load?), it from hex, and this would be used in connecting to libraries written in other languages and needs to be fast. A binary number with fractional binary digits is cool, but I don’t see a use case beyond that unfortunately; in fact, users working out how to do it themselves seems like a good way to tinker with Python and improve ones skills!

So, in my case, I needed it to have binary representation of a float,
to implement myself, exponentiation of any base, using binary exponent.

Because I didn’t know at first how to do that conversion,
I used decimal exponentiation of any base.

def root(x, k, tolerance = 1e-15):
    a = m = 2.0
    while abs(m) > tolerance:
        m = (a ** k - x) / (k * a ** (k-1))
        a -= m
    return a

def exp(base, x):
    a, b = int(x), x - int(x)
    result = base ** a
    for i in f'{b:.15f}'.split(".")[1]:
        base = root(base, 10)
        result *= base ** int(i)
    return result

So, I’ve tried to find which method could do binary conversion of a float.
So, that motivated me to ask for such a feature.

Now, because of Yours replies, I found a lot of new ideas, that could help.
Thank You very much! :seedling:

Please, do not forget that after all of You, Gods :innocent: of Python :snake:, come new babies :honeybee:,
so don’t make them to die and rise from death, to be able to convert a float to binary,
and binary to float! That is scary! :rose:

IIUIC, OP is not asking for this. Python has methods to show how floating-point numbers are packed in memory, or to load such memory fragment to:

>>> from struct import pack, unpack
>>> pack('d', 3.14)
b'\x1f\x85\xebQ\xb8\x1e\t@'
>>> unpack('d', _)
(3.14,)

Rather, to represent (parse) floating-point numbers in base=2 positional notation.

Well, for hexadecimal representation the major use case is ability to specify a (binary!) floating-point number exactly and unambiguously. That’s why float.fromhex() is used a lot in the CPython test suite.

Binary representation is same, just more verbose. Perhaps, this might have an educational value. See JuliaLang proposal: RFC: bit-float literal · Issue #9371 · JuliaLang/julia · GitHub.

Yes, that is what I mean.
Struct is low level C syntax, so for a simple python user, at least at the beginning,
that is kind to die and rise from death, only to be able to see a float to binary and binary to float.

We have integer to binary and binary to integer,
so same must be possible for float.