MySQL和SQLAlchemy ORM具有很高的数值精度 [英] High numerical precision floats with MySQL and the SQLAlchemy ORM

查看:74
本文介绍了MySQL和SQLAlchemy ORM具有很高的数值精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SQLAlchemy的ORM将一些数字存储在MySQL中.当我以后提取它们时,它们被截断,因此只保留了6个有效数字,从而使我的浮点数失去了很多精度.我想有一种简单的方法可以解决此问题,但我找不到方法.例如,以下代码:

I store some numbers in a MySQL using the ORM of SQLAlchemy. When I fetch them afterward, they are truncated such that only 6 significant digits are conserved, thus losing a lot of precision on my float numbers. I suppose there is an easy way to fix this but I can't find how. For example, the following code:

import sqlalchemy as sa
from sqlalchemy.pool import QueuePool
import sqlalchemy.ext.declarative as sad

Base    = sad.declarative_base()
Session = sa.orm.scoped_session(sa.orm.sessionmaker())

class Test(Base): 
    __tablename__   = "test"
    __table_args__  = {'mysql_engine':'InnoDB'}
    no      = sa.Column(sa.Integer, primary_key=True)
    x       = sa.Column(sa.Float)


a = 43210.123456789
b = 43210.0
print a, b, a - b

dbEngine = sa.create_engine("mysql://chore:BlockWork33!@localhost", poolclass=QueuePool, pool_size=20,  
                                 pool_timeout=180)              
Session.configure(bind=dbEngine)   
session = Session()            

dbEngine.execute("CREATE DATABASE IF NOT EXISTS test")
dbEngine.execute("USE test")  
Base.metadata.create_all(dbEngine)   

try:
    session.add_all([Test(x=a), Test(x=b)])
    session.commit()
except:
    session.rollback()
    raise

[(a,), (b,)] = session.query(Test.x).all()
print a, b, a - b

产生

43210.1234568 43210.0 0.123456788999
43210.1 43210.0 0.0999999999985

我需要一个解决方案来产生

and I would need a solution for it to produce

43210.1234568 43210.0 0.123456788999
43210.1234568 43210.0 0.123456788999

推荐答案

根据我们在注释中的讨论:sa.types.Float(precision=[precision here])代替sa.Float允许您指定精度;但是,sa.Float(Precision=32)无效.有关更多信息,请参见文档.

Per our discussion in the comments: sa.types.Float(precision=[precision here]) instead of sa.Float allows you to specify precision; however, sa.Float(Precision=32) has no effect. See the documentation for more information.

这篇关于MySQL和SQLAlchemy ORM具有很高的数值精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆