7

I want to do some math operations (+, -, *, /) on float32 rather than on float64 type. I need do these operations on number or numpy.array, and also some numpy math functions, such as sqrt mean. How do I do this?

1

2 Answers 2

16

Will numpy.float32 help?

>>>PI=3.1415926535897 >>> print PI*PI 9.86960440109 >>> PI32=numpy.float32(PI) >>> print PI32*PI32 9.86961 

If you want to do math operation on float32, convert the operands to float32 may help you.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes. numpy.float32 can help me. Are there any other methods to do this
Yes, when using an array you can call it's astype method if it is not float32: docs.scipy.org/doc/numpy/reference/generated/…
1

Use numpy.ndarray.astype:

import numpy as np arr_f64 = np.array([1.0000123456789, 2.0000123456789, 3.0000123456789], dtype=np.float64) arr_f32 = arr_f64.astype(np.float32) 

Pay attention to precision:

np.set_printoptions(precision=16) print("arr_f64 = ", arr_f64) print("arr_f32 = ", arr_f32) 

gives

arr_f64 = [1.0000123456789 2.0000123456789 3.0000123456789] arr_f32 = [1.0000124000000 2.0000124000000 3.0000124000000] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.