George
George

Reputation: 135

How to create a random string of floats?

Say I want a function f(angleDeg), that takes an array of angles in degrees from 0

import numpy as np
import random

def f(angleDeg):
    angleRad = angleDeg*np.pi/180
    return angleRad

Now I create these random numbers:

x = [random.randint(5,85) for _ in range(50)]
x = [float(i) for i in x]
f(x)

However, I get the error:

angleRad = angleDeg*np.pi/180
TypeError: can't multiply sequence by non-int of type 'float'

I now fixed it using Garret Hyde's second method, and I'm trying to raise exceptions for numbers not in the range, so I have:

if not (angleDeg > 0).all():
   raise ValueError("angle must be between 0 and 90")

And it gives me the error:

if not(angleDeg > 0).all():
AttributeError: 'bool' object has no attribute 'all'

Upvotes: 0

Views: 88

Answers (3)

Garrett Hyde
Garrett Hyde

Reputation: 5597

Part 1

Your function is trying to multiply an array by pi. You need to either iterate over the array or use numpy.array.

def f(angleDeg):
    angleRad = [x * np.pi / 180 for x in angleDeg]
    return angleRad

Or

def f(angleDeg):
    angleRad = np.array(angleDeg) * np.pi / 180
    return angleRad

Part 2

Again, you need to convert angleDeg from a standard array into a numpy.array.

angleDeg = np.array(angleDeg)
if not (angleDeg > 0).all():
    raise ValueError("angle must be between 0 and 90")

Upvotes: 1

robobrobro
robobrobro

Reputation: 320

Like others have said, you are trying to perform multiplication on a list, which does not support that operation. Change the line in f() from

angleRad = angleDeg*np.pi/180

to

angleRad = [deg*np.pi/180 for deg in angleDeg]

Upvotes: 1

Marcin
Marcin

Reputation: 238189

your x is array which you pass x. I think you meant this:

x = [f(i) for i in x]

or this:

x = list(map(f,x))

Upvotes: 0

Related Questions