Home > Enterprise >  How to work with the function that contains this product?
How to work with the function that contains this product?

Time:05-19

How to work with this equation :

def f(x,y):    
    return ( (7/10)*x**4 - 8*y**2   6*y**2   cos(x*y) - 8*x)


x = np.linspace(-3.1416,3.1416,100) 
y = np.linspace(-3.1416,3.1416,100) 
x,y = np.meshgrid(x,y) 
z = f(x,y) 

TypeError: only size-1 arrays can be converted to Python scalars

The problem is with the cos(x*y)

CodePudding user response:

You get that error when you pass a numpy array to math.cos.

>> import math
>> import numpy as np
>> x = np.random.random((3,3))
>> math.cos(x)

TypeError: only size-1 arrays can be converted to Python scalars

But if you use np.cos, you get the cosine for each element of x.

>> np.cos(x)
array([[0.77929073, 0.98196607, 0.99423945],
       [0.99542772, 0.93156929, 0.8161034 ],
       [0.62669568, 0.92407875, 0.76850767]])

So don't pass your numpy array to math.cos. Pass it to numpy.cos.

CodePudding user response:

Your x and y that you're passing to your function are likely not ints/floats, which based upon how you're using cos in the function they should be ints/floats. Just check that your x and y are actually what you expect them to be by printing them out. If they do end up being lists just iterate across the lists and call your function for each pair of x and y, or if you are expecting a singular value for x and y then you need to reconsider what you're doing prior to the f(x, y) call. It seems like there's a misunderstanding in what one of the functions you're using prior to your custom function call is actually doing.

CodePudding user response:

from math import cos

def f(x,y):
     return ( (7/10)*x**4 - 8*y**2   6*y**2   cos(x*y) - 8*x)
  • Related