Rounding output of sine function with format

Viewed 33

I'm trying to write a sine function that outputs answers going only to two decimal places. This is my code so far:

x=np.arange(0,190,10)
x_values=np.deg2rad(x)
y=np.sin(x_values)
y_values={":.2f"}.format(y)
print(y_values)

All the code through y works for me, when I do

print(y)

it outputs the correct values, but to like 10 decimal places, and I'd like to limit it to 2. I would like to do it using the .format notation, which I suck at. I'm getting an error that says "'set' object has no attribute 'format'," so there's some kind of fundamental misunderstanding I have about exactly how .format works. Is it only meant for strings? I would greatly appreciate any help I can get.

I did have a successful result using this:

y_values=[ '%.2f' % elem for elem in y ]

However, I'd like to see if it's possible to do it with .format. Thank you!

2 Answers

This should work for you:

y_values=[ '{:.2f}'.format(elem) for elem in y ]

I prefer f strings:

y_values=[ f'{elem:.2f}' for elem in y ]

The problem with your code was that the curly braces were outside the quotes and that y is a list. Moving the braces and using a list comprehension (as you showed in your last bit of code) are the two changes that fixed the issues you had.

You can create a universal vectorized function for this:

v_format = np.vectorize(lambda x, y: f'{x:.{y}f}')

# v_format(1, 2) returns
# array('1.00', dtype='<U4')

# v_format([15.2445, 154.5647, 35.6785], 2) returns
# array(['15.24', '154.56', '35.68'], dtype='<U6')

# v_format([15.2445, 154.5647, 35.6785], 4) returns
# array(['15.2445', '154.5647', '35.6785'], dtype='<U8')

# v_format([1.23, 3.456, 7.8910], [1, 2, 3]) returns
# array(['1.2', '3.46', '7.891'], dtype='<U5')

Work for every array with any numbers in it (even with complex ones).

* (If you need you can convert an array into a list or a tuple)

Related