Python Tensorflow添加浮点数可提供额外的数字

Python Tensorflow添加浮点数可提供额外的数字,python,tensorflow,precision,Python,Tensorflow,Precision,所以我想知道为什么我在添加它们时没有得到下面两个浮点数的总和。根据浮点的长度以及该点之前是否有非零数字,结果会有一个加或减的附加数字,或者它们不会被加。例如,下面的代码: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt with tf.Graph().as_default(): a = tf.Variable(1, name="Var_a") dx = tf.Variable(

所以我想知道为什么我在添加它们时没有得到下面两个浮点数的总和。根据浮点的长度以及该点之前是否有非零数字,结果会有一个加或减的附加数字,或者它们不会被加。例如,下面的代码:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

with tf.Graph().as_default():
    a = tf.Variable(1, name="Var_a")
    dx = tf.Variable(1.33333, name='dx')
    dt = tf.Variable(5e-10, name='dt')
    dz = tf.Variable(1.0, name='dz')


    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        a = dt+dx
        a = a-dz
        print dx.eval()
        print dt.eval()
        print (dt+dx).eval()
        print (dx+dt).eval()
        print a.eval()
        writer = tf.summary.FileWriter("/tmp/tensorlog")
        writer.add_graph(sess.graph)
给出以下结果:

>>>1.33333
>>>5e-10
>>>1.33333
>>>1.33333
>>>0.33333004

所以加法没有发生,减法也不能给出正确的结果。提前感谢您对此提出的任何意见

默认情况下,TensorFlow变量是32位浮点,它们没有足够的精度来跟踪差值
dt
,相对于其余值而言,差值太小。使用
dtype=tf.float64
提高精度,您将看到正确的结果:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

with tf.Graph().as_default():
    a = tf.Variable(1, name="Var_a", dtype=tf.float64)
    dx = tf.Variable(1.33333, name='dx', dtype=tf.float64)
    dt = tf.Variable(5e-10, name='dt', dtype=tf.float64)
    dz = tf.Variable(1.0, name='dz', dtype=tf.float64)


    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        a = dt+dx
        a = a-dz
        print dx.eval()
        print dt.eval()
        print (dt+dx).eval()
        print (dx+dt).eval()
        print a.eval()
        writer = tf.summary.FileWriter("/tmp/tensorlog")
        writer.add_graph(sess.graph)
输出:

1.33333
5e-10
1.3333300005
1.3333300005
0.33333000049999995
但是请注意,使用
tf.float64
而不是
tf.float32
值在内存和时间方面是有代价的,因此只有在确实需要高精度时才使用
tf.float64
。通常,32位浮点值精确到约7位小数,而64位浮点值精确到约15位小数