How to properly cast mpmath matrix to numpy ndarray ( and mpmath.mpf to float)

Question:

I’m working with mpmath python library to gain precision during some computations, but i need to cast the result in a numpy native type.

More precisely i need to cast an mpmath matrix (that contains mpf object types) in an numpy.ndarray (that contains float types).

I have solved the problem with a raw approach:

# My input Matrix:

matr = mp.matrix(
[[ '115.80200375',  '22.80402473',   '13.69453064',   '54.28049263'],
[  '22.80402473',   '86.14887381',   '53.79999432',   '42.78548627'],
[  '13.69453064',   '53.79999432',  '110.9695448' ,   '37.24270321'],
[  '54.28049263',   '42.78548627',   '37.24270321',   '95.79388469']])

# multiple precision computation
D = MPDBiteration(matr)

# Create a new ndarray  
Z = numpy.ndarray((matr.cols,matr.rows),dtype=numpy.float)

# I fill it pretty "manually"
for i in range(0,matr.rows):
    for j in range(0,matr.cols):
        Z[i,j] = D[i,j] # or float(D[i,j]) seems to work the same

My question is:

Is there a better/more elegant/easier/clever way to do it?

UPDATE:

Reading again and again the mpmath documentation I’ve found this very useful method: tolist() , it can be used as follows:

 Z = np.array(matr.tolist(),dtype=np.float32)

It seems slightly better and elegant (no for loops needed)

Are there better ways to do it? Does my second solution round or chop extra digits?

Asked By: Andrea Galloni

||

Answers:

Your second method is to be preferred, but using np.float32 means casting numbers to single precision. For your matrix, this precision is too low: 115.80200375 becomes 115.80200195 due to truncation. You can set double precition explicitly with numpy.float64, or just pass Python’s float type as an argument, which means the same.

Z = numpy.array(matr.tolist(), dtype=float)

or, to keep the matrix structure,

Z = numpy.matrix(matr.tolist(), dtype=float)
Answered By: user3717023

You can do that when vectorizing a function (which is what we usually want to do anyway). The following example vectorizes and converts the theta function

import numpy as np
import mpmath as mpm

jtheta3_fn = lambda z,q: mpm.jtheta(n=3,z=z,q=q)
jtheta3_fn = np.vectorize(jtheta3_fn,otypes=(float,))
Answered By: Maciej S.