"Solo las matrices de tamaño 1 se pueden convertir a escalares de Python"

Aug 21 2020

Tengo este codigo:

R = float(input("Enter the arc's radius of curvature: "))

H = float(input("Enter the arc's height: "))

import matplotlib.pyplot as plt

import numpy as np

import math

#cc = center of curvature

cc = math.sqrt(R**2 - (H / 2)**2)

x = np.linspace(-5,5,100)

y = math.sqrt(R**2 - (x - cc)**2)

plt.plot(x, y, 'c')

plt.show()

y obtenga este error:

TypeError: solo las matrices de tamaño 1 se pueden convertir a escalares de Python

¿Cómo puedo arreglar esto?

Respuestas

1 Valdi_Bo Aug 21 2020 at 12:27

Puede calcular y = math.sqrt(R**2 - (x - cc)**2)tanto como x en una sola variable, pero en su código intenta calcular esta expresión para cada elemento de la matriz x (y obtener una matriz de resultados).

To to this, proceed as follows:

  1. Define your expression as a function:

     def myFun(R, x, cc):
         return math.sqrt(R**2 - (x - cc)**2)
    
  2. Define vectorized version of this function:

     myFn = np.vectorize(myFun, excluded=['R', 'cc'])
    
  3. Compute y as:

     y = myFn(R, x, cc)
    

For R = 20.0, H = 30.0 and x = np.linspace(-5,5,10) (a shorter array) I got:

array([ 8.22875656, 10.34341406, 11.99128261, 13.34639903, 14.49112624,
       15.47223243, 16.31925481, 17.05218586, 17.6852162 , 18.22875656])