In: Computer Science
Question 1
Time and uncertainty in Python
Measure how long it takes to append values to a list and then convert that list to an array and compare this to how long it takes to concatenate the values to an empty array instead. You will do this comparison taking the uncertainty of each measurement into account. Write a Python script for the questions below.
As you will be working with individual times, use the perf_counter_ns function to work in nanoseconds instead of seconds.
(a) Time how long it takes to append the values. Use 10000 values.
Collect a data set of 100 measured values.
Plot this data in a histogram and fit a Gaussian distribution to it. Does the Gaussian distribution look like the best distribution for this? (That question is rhetorical, you may continue using the Gaussian).
Save the plot
Calculate the best approximation for the time taken to perform the append method and it's associated uncertainty (you will quote this later).
(b) Now perform the same steps above for the concatenate method.
(c) Now, quote the best approximation of the time taken and the associated uncertainties for each of the methods. Is it clear that one outperforms the other? Why?
Hint: To perform the concatenation, your code can look like:
array = np.concatenate((array, np.array([value])))
For this above question, here is the answer below. A): For time perf_counter we can take this example: from time import perf_counter n, m = map(int, input().split()) t1_start = perf_counter() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # For Stop the stopwatch / counter t1_stop = perf_counter() print("Elapsed time:", t1_stop, t1_start) print("Elapsed time during the whole program in seconds:", t1_stop-t1_start)
B) For Concatenating and Joining Strings,The simplest and most common method is to use the plus symbol (+) to add multiple strings together. Simply place a + between as many strings as you want to join together:
>>> 'a' + 'b' + 'c'
'abc'
In keeping with the math theme, you can also multiply a string to
repeat it:
>>> 'do' * 2
'dodo'
Remember, strings are immutable! If you concatenate or repeat a
string stored in a variable, you will have to assign the new string
to another variable in order to keep it.
>>> orig_string = 'Hello'
>>> orig_string + ', world'
'Hello, world'
>>> orig_string
'Hello'
>>> full_sentence = orig_string + ', world'
>>> full_sentence
'Hello, world'
If we didn’t have immutable strings, full_sentence would instead
output 'Hello, world, world'.
C) We can use this below function to achieve this target.
array = np.concatenate((array, np.array([10000])))