Chapter 8

Computing Using Math

IN THIS CHAPTER

check Using math operations

check Getting fancy with advanced operations

check Modding, ordering, and rounding numbers

check Coding a crypto code breaker

Math operations consist of everything from adding and multiplying to using exponents. This chapter helps you gain proficiency in working with math operations, coaching you in how you can use these computational tools in your computer programs. For example, your coder can write code that uses math to find the average of a group of test scores, or figure out whether a number is even or odd, or pick random numbers for a dice roll.

Acting Out Math, Unplugged

Math is something you use every day. You figure out how many quarts of paint you need to cover all four walls of your room. You divide dog bones to make sure each beagle and corgi gets his fair share. You compute a tip to reward the pizza delivery person for getting that large pepperoni to you fast and hot (see Figure 8-1). Speaking of fast and hot, fast is determined by a number — a relative quantity of time; and hot is determined by a temperature.

image

FIGURE 8-1: Math quantities appear everywhere in daily life.

Here are some other numerical quantities and computations that is performed with math:

  • Weighing a baby at the pediatrician’s office to determine her rate of growth
  • Paying for movie tickets and snacks at the theater
  • Measuring the time it takes for a student athlete to run a sprint or a marathon
  • Carefully scooping out the right quantity of each ingredient for a recipe.
  • Determining how many cells exist after a single cell divides several times

Number types

When working with math operations in your code, your coders need to know about the different types of numbers they can use. Each number type is suited to a different purpose:

  • Integers are negative numbers, zero, or positive numbers. They don’t have decimal place digits. Integers can be used for a variety of purposes. They can indicate position on a number line or a coordinate grid. They can be used to count things. They can be used to count the number of likes on a YouTube video! In programming languages that require a number type to be declared, the code for an integer is typically int.
  • Decimals are numbers that have a decimal point and digits after the decimal. They can be negative, zero, or positive in value. Decimals are used for number quantities that require precision. Weight, salaries, land acreage, and clocks measuring elapsed times at sporting events. In programming languages that require a number type to be declared, the code for a decimal number is typically double.

See Chapter 7 for more information on number typing.

Dramatizing math

To understand mathematics and math operations in coding, try some math activities, unplugged. Play a board game with your coder. (See Figure 8-2.) Almost all board games involve rolling dice, summing their values, and moving a marker around the board to build counting skills. Playing dominoes does as well. Games such as Monopoly also involve buying and selling and can help your coder in working with currency. Card games such as twenty-one and Old Maid help players build skills in probability as they try to determine the chances on drawing the cards they want, or don't want. In this age of apps and video games, you may also find that you and your coder enjoy a little game time that doesn’t involve screen time!

Doing Simple Math

In most programming languages, math operations are already built-in so that your coder can simply use them when needed. However, in other languages, some math operations may needed to be activated at the start of the program before you can use them.

Using pseudocode

Programming languages follow the same general rules with regard to performing math operations. Table 8-1 shows general pseudocode for these operations with an example of integers and decimals.

TABLE 8-1 Pseudocode for Basic Math Operations

Operation

Pseudocode

Examples

Add two numbers

number1 + number2

23 + 5

2.78 + 1.2

Subtract two numbers

number1 – number2

13 - 28

4.22 – 9.00

Multiply two numbers

number1 * number2

33 * 12

5.34 * 6.7

Divide two numbers

number1 / number2

12 / 4

5.5 / 2.0

Combining simple operations

number1 * number2 * number3

5 * 6 * 10

6.5 * 3.25 * 0.75

Using Scratch

Scratch, similar to other block-based coding languages, has simple blocks that support basic math operations, as shown in Figure 8-3. Scratch supports adding integers and decimals.

image

FIGURE 8-3: Scratch provides blocks for basic math operations.

Scratch also supports combining simple math operations. Figure 8-4 shows a set of blocks that adds four numbers together.

image

FIGURE 8-4: Scratch allows you to combine basic math operations.

tip One thing to point out to young coders when they're writing in a block-based language such as Scratch is that to add four numbers, you only need three add blocks.

Using Python

Basic math operations in Python look very similar to pseudocode. This makes sense, considering Python aimed to be a language that was approachable and familiar for humans (see the sidebar about Guido van Rossum in Chapter 3). Python supports math operations for integers and decimals, although in Python a decimal is called a float. For adding, subtracting, multiplying, and dividing, you would follow the pseudocode (refer to Table 8-1). For example, addition in Python for integers and floats is like this:

3 + 5

2.78 + 1.2 + 5.6

remember This is actually true for most text-based languages. For example, that’s exactly how you would add two numbers in Java and JavaScript as well!

Doing Advanced Math Operations

Although you can do a lot with adding, subtracting, multiplying, and dividing, sometimes you need more advanced mathematical operations. Additional operations that might come in handy are changing the sign of a number, finding the exponent, computing absolute value, and calculating the square root, as well as combining math operations with variables.

Using pseudocode

Just like the basic math operations in the previous section, more advanced math operations can support integers and decimals in almost all programming languages. Table 8-2 shows examples of how you might write code for changing the sign of a number, and for other advanced math operations. It also shows how to write pseudocode when using variables in advanced math operations.

TABLE 8-2 Pseudocode for Advanced Math Operations

Operation

Pseudocode

Examples

Change the sign of a number

-1* number1

-1 * (-13)

-1 * 4.22

Using exponents

number1 ^ number2

3 ^ 5

2.78 ^ 1.2

Getting the absolute value

|number1|

|13|

|-4.22|

Getting the square root

√number1

√16

√9.4

Assigning values to variables

int number1 = value1 int number2= value2

int number1 = 5

int number2 = 9

Using variables in math operations

int product = number1 * number2

int product = 45

Assigning values to variables

double height = value3 double width = value4

height = 2.4

width = 6.0

Using variables in math operations

double perimeter = 2*height + 2*width

perimeter = 16.8

Turn to Chapter 7 to find out how to declare a variable and how to give a variable a new name.

Using Scratch

Scratch provides users with a number of math operations beyond the basic four. Figure 8-5 shows how to change the sign of a number: multiply the number by negative one (-1). In this way, a positive number becomes negative, and a negative number becomes positive.

image

FIGURE 8-5: How to negate a value in Scratch.

Finding an exponent in Scratch can also be a bit tricky. There isn't a simple block for number1number2. There are two blocks for exponent functions, shown in Figure 8-6, but are specific to enumber1 and 10number1. These blocks can be found under Operations (see Figure 8-7). To write the function for number1number2, you basically have to write all the multiplications, also shown in Figure 8-6.

image

FIGURE 8-6: Three ways of finding the exponent in Scratch.

image

FIGURE 8-7: Exponent, absolute value, and square root in Scratch.

Scratch makes a lot of the other advanced math operations very easy! Finding the absolute value and square root of a value uses one block, which can be found under the Operations category. Figure 8-7 shows the block and all the choices you have for it. Absolute value is represented as abs and square root is represented as sqrt. The block starts as sqrt.

Combining variables with math operations in Scratch is really easy. Basically, anywhere there is a circular opening you can either type a number or drag in a variable. For example, Figure 8-8 shows some of the math operations throughout this chapter using variables.

image

FIGURE 8-8: Examples of variables being used to solve advanced math operations in Scratch.

Using Python

Negating a number, finding the exponent, absolute value, and square root in Python are all straightforward. You can perform all three operations on integer or decimal (float) numbers.

Negating a number in Python pretty much only makes sense if you're trying to negate the value of a variable; otherwise you would just use the positive or negative number. Although, you can still negate a number directly, just add parenthesis for clarity:

-(number1)

Examples

-(5)

-(-8.99)

Exponents are pretty much the same as the basic math operations (like adding) and use a special symbol:

number1 ** number2

Examples:

3 ** 5

2.78 ** 1.2

Getting the absolute value of a number in Python requires you to use a function. Functions in Python (and other text-based languages) are special commands or subprograms that you call in your code. Typically, you pass the function a parameter (a value for the function to use in a computation) and the function returns an output value to you. You might have already encountered some functions if you worked through earlier chapters in this book. For example, a function in JavaScript from Chapter 5 is:

getXPosition("character");

Here’s the Python code for absolute value:

abs(number1)

Examples are

abs(-7)

abs(8.9)

Finding the square root of a number is even a little more complicated than finding the absolute value when coding in Python. First, you have to import a Math library so that Python knows how to evaluate this method (which is another type of subprogram you can call in Python).

import math

math.sqrt(number1)

Examples are

import math

math.sqrt(16)

math.sqrt(99.89)

For additional information on subprograms your coder can write in his code, see Chapter 12.

Finally, using variables in more advanced Python math operations is very similar to using them in Scratch — basically you replace numbers with variables! A couple examples are here:

Finding the absolute value with variables:

costOfTable1 = 66.89

costOfTable2 = 90.54

differenceInCost = abs(66.89 – 90.54)

Finding the square root with variables:

areaOfSquareRoom = 196

lengthOfOneWall = math.sqrt(areaOfSquareRoom)

Oh So Mod — Using the Mod Operation

Another useful operator that can be tricky for young coders at first is modulo, also referred to as modulus and mod. The mod of two numbers is the remainder after a division of two numbers.

This operator can be useful for writing applications based on real-world scenarios. For example, say you have $20.00. You want to pass out exactly $3.50 to as many friends as possible, and you want to know how much money you will have leftover. So you would want to solve the questions “What is the quotient of 20.00/3.50?” and “What is the remainder of 20.00/3.50?” The answer to this word question would be “You can give 5 friends $3.50 and you will be left with $2.50.”

tip What is really great is that Google provides a mod function on its online calculator! So if you and your coder are ever debugging (see Chapter 12), you can check your mod equation on Google fairly easily. Just go to google.com and type “number1 % number2” and the calculator appears with your answer. For example, Figure 8-9 shows checking 63 % 19. There is even a button for mod on the calculator; it’s the % symbol.

image

FIGURE 8-9: Using Google, you can check the result of the mod operator.

Using pseudocode

Mod in pseudocode is often represented with the % symbol, because that is most commonly used in text-based languages like Python and Java.

number1 % number2

Examples are

30 % 7

6.89 % 5.9

Using Scratch

In Scratch, you can find a mod block under the Operators category. For example, Figure 8-10 shows the mod block evaluating 9 mod 8, which equals 1.

image

FIGURE 8-10: The mod block found in the Scratch Operators category.

Using Python

In Python, the mod operator is very similar to the basic math operations such as adding, subtracting, multiplying, and dividing. You simply use the % symbol between the numbers. It's exactly like the pseudocode examples for both integers and decimals.

Ordering Those Operations (PEMDAS)

Most programming languages follow the standard math order of operations, often referred to as PEMDAS: Parenthesis, Exponent, Multiplication, Division, Addition, Subtraction, from left to right. However, it’s common practice in coding to use additional parentheses to help ensure the correct order is being followed.

Using Scratch

Because Scratch doesn’t have a parenthesis symbol, it behaves differently when it comes to the order of operations. Basically, each individual block is evaluated first because each block is basically representing an operation within parentheses. For example, Figure 8-11 shows a compound math operation using addition and division. The order of operations for Figure 8-11 written in pseudocode is:

8 + 6

10 + 14

24 / 3

aveScore = 8

image

FIGURE 8-11: Order of operations example in Scratch with addition and multiplication.

It can also be viewed all in one line like this:

aveScore = (10 + (8 + 6)) / 3

Using Python

Python follows the PEMDAS rule, although two operations aren’t accounted for in PEMDAS; negation and mod. Negation (N) comes after parenthesis, but before exponents: PNEMDAS. Mod (m) is at the same level as multiplication and division: PNEMDmAS. Some examples of how Python would evaluate compounded math operations are here:

Compound math operation without parenthesis:

print( 5 * 9 % 8 + 9 / 3 )

8

The steps that Python takes are:

5 * 9 = 45

45 % 8 = 5

9 / 3 = 3

5 + 3 = 8

Compound math operation with parentheses result in a different computation:

print( 5 * ((9 % 8) + 9) / 3 )

16

The steps that Python takes are:

9 % 8 = 1

1 + 9 = 10

5 * 10 = 50

50 / 3 = 16

Rounding

Rounding in coding can get a little tricky because of the two types of numbers that are often used: integers and decimals. If you’re using math operations on integers only, then the resulting answer will also be computed as an integer.

remember The only time when integers round is during division, and programming languages tend to round down, regardless of what the remainder is. For example:

14 / 3 = 4

15 / 3 = 5

16 / 3 = 5

When working with decimals only in math operations, programming languages typically evaluate the operation and might vary between languages and machines for how precise the result is. For example:

14.00 / 3.0 = 4.666667

15.0 / 3.00 = 5.0

16.77 / 3.99009 = 4.20291271625

When combining integers and decimals is where it can get interesting. Typically programming languages default to the most precise result. So if you add an integer and a decimal, the result typically is a decimal. For example:

60.8 + 7 = 67.8

Rounding via casting in Java

In a typed programming language, where you specify what type the values are that you’re using, you can explicitly cast either the number in the operator, or the result to an integer or a decimal. Casting means to tell the computer explicitly what type you want a value to be, instead of letting the computer determine what type a value is based on its properties. Notice in the following examples that programming languages typically round down, regardless of how close to the next integer the decimal is. For example, in Java you might have the following:

(int)60.8 + 7;

67

int sum = (int)(89.333 + 1.555);

sum = 90

int sum = (int)(89.3 + 1.7);

sum = 91

double quotient = (double)8 / 3;

quotient = 2.6666666666666665

double quotient = (int)8.4 / 3;

quotient = 2.0

When adding precision, you can perform explicit or implicit casting. Implicit casting is when the programming language adds precision to numbers based on all the numbers being used in the operation. Explicit casting is described in the section coming up.

double quotient = 8 / 3;

quotient = 2.0

double quotient = 8.0 / 3;

quotient = 2.6666666666666665

Rounding decimals to integers via methods

Although rounding occurs often between integers and decimals during math operations, most programming languages also have a rounding method that can be used to explicitly round decimals to the nearest integer. This is the same in standard math operations:

5.5 = 6

5.4999 = 5

Figure 8-12 shows a few examples of rounding in Scratch.

image

FIGURE 8-12: Example of using the round math operator block in Scratch.

The following table shows a couple rounding examples in both Python and Java:

Language

Example

Result

Python

round(5.5)

6

Python

round(5.4999)

5

Java

Math.round(5.5);

6

Java

Math.round(5.4999);

5

Some programming languages even have functions that let you round to a certain decimal! For example, Python's round function can be extended to include a second parameter where you specify how many digits after the decimal you want the number rounded to:

round(5.5985, 2)

5.60

round(5.46732, 4)

5.4673

Generating and Using Random Numbers

Being able to use random numbers can be a lot of fun when writing interactive programs. Random numbers can help you and your young coder create a dice rolling simulation, or make a game where each gem that is collected gives you a random number of points, or even create scattering where many sprites are positioned in random locations onscreen!

Using pseudocode

When trying to find a random number between two numbers, it’s important to know whether you’re including the two numbers that are your boundaries, or not including them. For example, a random number between 1 and 5 inclusive could be 1, 2, 3, 4, or 5. While a random number between 1 and 5 exclusive could only be 2, 3, or 4. You might also want to decide to include the first number, but not the last. For example, a random number between 1 and 5 including 1 but excluding 5 could be 1, 2, 3, or 4. To specify this with pseudocode, you would typically use the symbol [ to denote inclusivity of the number and ( to denote exclusivity.

The functions (with examples) needed to choose a random number are:

Pseudocode

Examples

random(number1, number2)

random(1, 100) -> 2…99

random[number1, number2]

random[1, 100] -> 1…100

random(number1, number2]

random(1, 100] -> 2…100

random[number1, number2)

random[1.5, 100) -> 1.5, 1.6, 1.7 … 99.7, 99.8, 99.9

Using Scratch

Scratch provides an easy to use the random block under the Operators category, as shown in Figure 8-13. Scratch's random block is inclusive. The random block returns an integer if both values given are integers, and returns a decimal even if one of the numbers is a decimal. The precision of the decimal matches that of the most precise parameter given.

image

FIGURE 8-13: Example of using the random operator block in Scratch.

Using Python

To use the random function in Python, you have to first import the random library. You can then call the randint function to find a random integer or the uniform function to find a random float (decimal). Both the randint and uniform functions are inclusive.

Functions (with examples) to choose a random number are:

Python

Examples

randint(number1, number2)

randint(1, 100)

uniform(number1, number2)

uniform(5.5, 6.8)

Coding a Crypto Code Maker

After you and your young coder have a handle on the different math operations that are available to you in coding, it can be really fun to find ways to create fun programs that use those operations! One that doesn’t always come to mind is making a cipher! Ciphers are a lot of fun to build because they can offer additional play outside of building the program — you and your coder can write letters to each other using the secret code that only the cipher you built can solve!

Building a simple crypto code maker in Scratch is actually pretty quick! The cipher built in this section is also known as a Caesar Cipher. Basically you give a shift amount and a letter and the program moves through the alphabet by the shift amount, looping around to A if it gets to Z, and gives you the secret letter. For example, if you wanted to tell your young coder the plaintext word “hi,” you could use a shift to move each letter to a new position in the alphabet, obscuring the original message. With a shift of 6, the plaintext, “hi” becomes the ciphertext word “NO.”

It might be a good idea to play this game with a paper and pencil with your young coder before you start coding, because then you have an idea of what needs to be built! You can even have your young coder write the steps that they use to figure it out as they play with the unplugged version!

To build the crypto code maker in Scratch, follow these steps:

  1. Create a list called “letters” in Scratch that contains all 26 letters.

    You can check out Chapter 11 for more explanations on lists.

  2. Create four variables that will keep track of the ciphertext (output), plaintext (input), shift, and position of the counter used during the algorithm.

    Your list and these four variables are visible under the Data category, as shown in Figure 8-14. You can find out more about variables in Chapter 7 if you need a refresher.

    tip Make sure your ciphertext, plaintext, and shift amount variables and your letters list are visible on the stage by selecting the check box next to them. Because the position variable is keeping track of the position as you iterate through the alphabet, it doesn’t have to be visible on the stage, so make sure you uncheck the box next to it. Your stage should look something like Figure 8-15.

  3. Ask the user for the plaintext letter and the shift amount. Be sure to save the answers from the user in the appropriate variables.

    Figure 8-16 shows how to ask and save the responses.

  4. Starting at position 1 in the list (A), iterate through the list of letters until you reach the letter that the user submitted.

    When this loop ends, the variable position holds the number that corresponds with the plaintext letter given by the user (for example, 1 is A, 2 is B, and so on).

  5. Add the shift amount to the position, then mod by 26.

    You have to mod by 26 to allow the cipher to start back at A if it reaches Z. For example, if the plaintext letter the user submits is X and the shift is 6, the ciphertext is D. You can evaluate this mathematically as well: X is at position 24. 24 + 6 is 30. 30 % 26 is 4. 4 is the position of letter D.

  6. Get the ciphertext letter from the list, and display it to the user.
image

FIGURE 8-14: The four variables and one list you need in your crypto code maker code.

image

FIGURE 8-15: The stage of your crypto code maker should be similar.

image

FIGURE 8-16: The completed code for the Scratch crypto code maker.

All the code for this entire code maker is shown in Figure 8-16.

tip As a bonus challenge, can you have your young coder figure out how to make a reverse version of this program? See if he can build a version to convert ciphertext into plaintext!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.219.217