Problem when performing the calculation between arrays

Asked

Viewed 47 times

0

I’m building a code that has a very similar structure to the code below.

from math import sin, pi
from numpy import zeros
djn = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
djn = array(djn)

def test(djn):
   M = len(djn)
   delta = zeros(M, float)
   delta[0:M] = 0.409279709 * sin(((2*pi)/365)*(284+djn[0:M]))
   return delta

res = test(djn)

The idea is that the function argument is an array as well as the output of it. However I have gotten the following error:

only size-1 arrays can be converted to Python scalars

But I’ve seen structures like this and I can’t see my mistake.

Thank you for your cooperation :)

  • 1

    The only problem with the above code is that you are not loading array, sin and pi. Behold here. However if the code is different and the error you put is what happens in the other code, use the np.vectorize

  • I ended up not putting, but was using the sin and the pi of math and not of numpy

  • 1

    use the sin of numpy. That alone is enough to solve the problem

  • @Syner I know it’s not related to the problem, but I also realized that you wrote a term 2*pi/365 inside the sine and was wondering if it would not be 360 because it looks like you wanted to convert degrees to radian, right?

1 answer

0

You are getting the error "only size-1 arrays can be converted to Python scalars" because the function expects a single value instead, you passed an array.

use the library of numpy in place of the Math.

import numpy as np

djn = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
djn = np.array(djn)

def test(djn):
   M = len(djn)
   delta = np.zeros(M, float)
   delta[0:M] = 0.409279709 * np.sin(((2*np.pi)/365)*(284+djn[0:M]))
   return delta

res = test(djn)
print(res)
  • 1

    I’m sorry but there’s an error in your code. djn has to be inside the sine. You did sin(2pi/365)*djn, but it was meant to be sin(2pi*djn/365)

  • @Flaviomoraes, truth I ended up removing relatives.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.