Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i set float128 as the standard float-array in numpy

So I have a problem with my numerical program, and I'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into float128 arrays, without going through my code and typing dtype='float128' all over the place. My arrays are all float64, but i never explicitly wrote dtype='float64', so i was hoping there was a way to change this default behavior.

like image 851
Eskil Avatar asked Mar 18 '11 09:03

Eskil


People also ask

How do I change the Dtype of a NumPy array?

In order to change the dtype of the given array object, we will use numpy. astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.

What is the default data type of NumPy array?

The default data type: float_ . The 24 built-in array scalar type objects all convert to an associated data-type object.

Are Python floats 32 or 64?

Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np. float64 . In some unusual situations it may be useful to use floating-point numbers with more precision.

Can NumPy array have different data types?

While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous.


1 Answers

I don't think there is a central "configuration" you could change to achieve this. Some options what you could do:

  1. If you are creating arrays only by very few of NumPy's factory functions, substitute these functions by your own versions. If you import these functions like

    from numpy import empty
    

    you can just do

    from numpy import float128, empty as _empty
    def empty(*args, **kwargs):
        kwargs.update(dtype=float128)
        _empty(*args, **kwargs)
    

    If you are doing

    import numpy
    

    you can write a module mynumpy.py

    from numpy import *
    _empty = empty
    def empty(*args, **kwargs):
        kwargs.update(dtype=float128)
        _empty(*args, **kwargs)
    

    and import it like

    import mynumpy as numpy
    
  2. Refactor your code to always use dtype=myfloat. This will make such changes easy in the future. You can combine this approach with the use of numpy.empty_like(), numpy.zeros_like() and numpy.ones_like() wherever appropriate to have the actual data type hardcoded in as few places as possible.

  3. Sub-class numpy.ndarray and only use your custom constructors to create new arrays.

like image 186
Sven Marnach Avatar answered Sep 25 '22 10:09

Sven Marnach