asyncpg icon indicating copy to clipboard operation
asyncpg copied to clipboard

Whenever i create a table with a `real` column and read the value i get something different then what i saved

Open cldtech opened this issue 1 year ago • 1 comments

  • asyncpg version: 0.29.0
  • PostgreSQL version: 15.6
  • Do you use a PostgreSQL SaaS? If so, which? Can you reproduce the issue with a local PostgreSQL install?: No
  • Python version: 3.12
  • Platform: Debian 12
  • Do you use pgbouncer?: No
  • Did you install asyncpg with pip?: Yes
  • If you built asyncpg locally, which version of Cython did you use?: N/A
  • Can the issue be reproduced under both asyncio and uvloop?: Yes

Hi, i'm not completely sure if this is a bug but it's certainly not the behavior i expected. Whenever i create a table with a real column and read the value i get something different then what i saved.

Example 1:

import asyncpg
import uvloop

async def main():
    conn = await asyncpg.connect('postgresql://postgres:RGB2.4GHz@localhost:5432/test')
    
    # Execute a statement to create a new table.
    await conn.execute('''
        CREATE TABLE users(
            id serial PRIMARY KEY,
            name text,
            test real
        )
    ''')

    # Insert a record into the created table.
    await conn.execute('''
        INSERT INTO users(name, test) VALUES($1, $2)
    ''', 'Bob', 45.542154)

    # Select a row from the table.
    row = await conn.fetchrow(
        'SELECT * FROM users WHERE name = $1', 'Bob')
    # *row* now contains
    # asyncpg.Record(id=1, name='Bob', dob=datetime.date(1984, 3, 1))
    print(row.get("test"))

    # Close the connection.
    await conn.close()

uvloop.run(main())

This print 45.542152404785156. What am i doing wrong, is this a bug in the data conversion to python float? I tried with a double precision column and it works fine. Only the real column. Is the real type not supported by asyncpg?

cldtech avatar Apr 10 '24 05:04 cldtech

This is how floating point numbers work. You can try yourself in psql

=> select 45.542154::real::double precision;
       float8
--------------------
 45.542152404785156
(1 row)

You get the same result with numpy in Python even without postgres.

Floating point values always have some inaccuracy. If you need to preserve exact values, you should use numeric or at least double precision.

eltoder avatar Jul 20 '24 16:07 eltoder