Mathematical Operations
A really powerful way to use python is for computations of arrays. In this next section you will see a few examples of how quickly python can compute elements in the array.
Here is the official documentation of the various operations that can be done using NumPy.
Let's apply your knowledge of arrays and how we can use Python to code vectorized mathematical commands such as addition, subtraction, multiplication, exponents, and square roots.
Follow the example problems below and click the coding assistance links below, as needed.
MATHEMATICAL OPERATIONS #1
MATHEMATICAL OPERATIONS #1 Practice
Image that you have x equaling all the integers from 1 to 20.
Step 1: Run the code to see the values of x.
Click ▶
Step 2: Next, you want to multiply each of those by 10. Add the following lines of code to multiply "The array by 10.
print()y=x*10 print ("This is 10 times x")print(y)Click ▶
Step 3: Alter this code to have the x array go from 1 to 200,000.
Click ▶
Step 4: Use the sum(y) command to add all the items in the element. Print the total.
MATHEMATICAL OPERATIONS #2
Multiplication, Division, and Exponents
MATHEMATICAL OPERATIONS #2 Practice
The variable name is "amount_of_candy_for_each_child."
Step 1: Write Code to raise each element to the power of 4. (i.e. If an element is 2, the output would be 2x2x2x2 = 16 for that element in the output array)
Click ▶
Step 2: Make a second output array this time dividing each element by 22.7.
Step 3: Index to find the second to last element of the output array from Step 2.
Coding Assistance: Click this link if you need help solving this problem. (Answers should look like the output below.)
MATHEMATICAL OPERATIONS #3
CREATING AN ARRAY FROM AN EQUATION
MATHEMATICAL OPERATIONS #3 PRACTICE
The equation is y = ((x + 7) * 3)
Step 1. Use the linspace (and its default) to create an x array from 7 to 4000.
Step 2. Write the code to calculate the y array.
Step 3. Use the f-statement to print out "The y values are : " .......
Step 4. Add the following Code to help you print your plot. Click Run.
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x,y)
plt.title("Numbers")
plt.show()
(Note: We will be learning these 5 lines of code in the upcoming modules. For now, it's ok to just copy and use the coe).