2

I am aware of howto force python operations to work on float32: How to force python float operation on float32 rather than float64

But there is no Q or A about forcing the built in functions to work on float32. I wanted to ask how about forcing the built-in math or numpy functions such as math.sqrt or numpy.sqrt to work on float32. FYI, I could not comment on the question yet.

In theano, we can easily configure the function, e.g., sqrt to work on float32 or float64 as follows:

from theano import config
config.floatX = 'float32'
from theano import tensor as T
x = T.scalar()
a = T.sqrt(x)

from theano import function
h = function([x], a)
print h(15)

and the result is:

3.87298345566

Now I tried to force math.sqrt and numpy.sqrt to do the same as follows:

import math
import numpy
print math.sqrt(numpy.float32(15))

But the result is still seems in float64 (I confirmed it that the result would be the same, i.e., 3.87298334621, if I set theano.config.floatX='float64'):

3.87298334621

I am curious to know howto force math.sqrt, numpy.sqrt to work on float32?

4

1 回答 1

4
>>> type(numpy.sqrt(numpy.float32(2)))
<type 'numpy.float32'>

numpy.sqrt已经做了你想要的。另一方面,这些math函数总是将它们的输入转换为float并返回float,没有选项可以改变它。坚持使用 NumPy 操作而不是mathNumPy 数据类型的模块,你应该没问题。

于 2014-06-15T02:10:54.737 回答