Home > Software engineering >  Type Error: Field elements must be 2- or 3-tuples when implementing Numpy array
Type Error: Field elements must be 2- or 3-tuples when implementing Numpy array

Time:07-08

I'm new to Numpy. I have the following variables:

import numpy as np

arr = np.array([[3, 5, 9], [1, 2, 3]]).T
Dr = 2
Dl = 3
Db = 4

delta_R = arr[0, 0]
delta_L  = arr[1, 0]
delta_B = arr[2, 0]
delta_theta = (delta_L - delta_R) / (Dr   Dl)

I'm attempting to implement the following equation:

enter image description here

To do so, I've written:

delta_x_delta_y_arr = np.array([2*np.sin(delta_theta/2) * np.array([(delta_B / delta_theta)   Db], [(delta_R / delta_theta)   Dr])])

Firstly, I'm not certain whether I've expressed this equation properly using Numpy arrays. If I have, why do I see the following traceback?

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5072/2142976421.py in <module>
----> 1 delta_x_delta_y_arr = np.array([2*np.sin(delta_theta/2) * np.array([(delta_B / delta_theta)   Db], [(delta_R / delta_theta)   Dr])])

TypeError: Field elements must be 2- or 3-tuples, got '9.5'

Thanks in advance for any assistance you can give this Numpy newbie!

CodePudding user response:

The NumPy array should be np.array([[...], [...]]) rather than np.array([...], [...]). Try

delta_x_delta_y_arr = 2*np.sin(delta_theta/2) * np.array([[(delta_B / delta_theta)   Db], [(delta_R / delta_theta)   Dr]])

instead.

CodePudding user response:

Your np.array argument is too long to readily read - and write correctly. Extracted, and edited for clarity:

 np.array([2*np.sin(delta_theta/2) * 
          np.array([(delta_B / delta_theta)   Db],
                   [(delta_R / delta_theta)   Dr])
 ]

The inner array has 2 list arguments. https://stackoverflow.com/a/72905294/901925 is right in saying that it is wrong. Here's why:

The signature for np.array is:

array(object, dtype=None, ...)

So it's trying to interpret the 2nd list as a dtype. A typical compound dtype looks like:

[('f0',int), ('f1',float,3)]

In other words, if the dtype is a list, it expects tuples, with 2 or 3 elements.

Field elements must be 2- or 3-tuples, got '9.5'

I haven't seen this error before, but based on what I know about making structured arrays, this makes sense. In cases like this, it's a good idea to double check your arguments against the function documentation.

And avoid overly long lines.

  • Related