Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a number to a chosen integer

In Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12] Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far.

import numpy as np

def roundGrade(grades):    
    if (-5<grades<-1.5):
        gradesRounded = -3
    elif (-1.5<=grades<1.5):
        gradesRounded = 00
    elif (1.5<=grades<3):
        gradesRounded = 2
    elif (3<=grades<5.5):
        gradesRounded = 4
    elif (5.5<=grades<8.5):
        gradesRounded = 7
    elif (8.5<=grades<11):
        gradesRounded = 10
    elif (11<=grades<15):
        gradesRounded = 12
    return gradesRounded

print(roundGrade(np.array[-2.1,6.3,8.9,9]))

Our console doesn't seem to like this and retuns: TypeError: builtin_function_or_method' object is not subscriptable

All help is appreciated, and if you have a smarter method you are welcome to put us in our place.

like image 963
T.DOGG Avatar asked Jun 17 '16 09:06

T.DOGG


People also ask

What does round to integer mean?

Rounding to the nearest integer is really rounding to the nearest units place. Sometimes, you will be asked to round to the nearest hundreds, or to the nearest hundredths — to some decimal place other than the units place. The rule is just a more generalized version of the previous rounding rule.

How do you round the number 7.25 to the nearest integer in JavaScript?

The Math. round() function in JavaScript is used to round the number passed as parameter to its nearest integer. Parameters : The number to be rounded to its nearest integer.

How do you round an integer in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.


1 Answers

You are getting that error because when you print, you are using incorrect syntax:

print(roundGrade(np.array[-2.1,6.3,8.9,9]))

needs to be

print(roundGrade(np.array([-2.1,6.3,8.9,9])))

Notice the extra parentheses: np.array(<whatever>)

However, this won't work, since your function expects a single number. Fortunately, numpy provides a function which can fix that for you:

In [15]: roundGrade = np.vectorize(roundGrade)

In [16]: roundGrade(np.array([-2.1,6.3,8.9,9]))
Out[16]: array([-3,  7, 10, 10])

http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.vectorize.html

like image 120
juanpa.arrivillaga Avatar answered Sep 19 '22 14:09

juanpa.arrivillaga