• No results found

CHAPTER 6. Functions and Math Expressions

N/A
N/A
Protected

Academic year: 2021

Share "CHAPTER 6. Functions and Math Expressions"

Copied!
17
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

Introduction

Functions are an effective tools used in many programming languages.

Functions provide the information required to carry out tasks and are used to perform operations in input values and provide us with necessary information. In this section, we will introduce functions and explain how they are used with expressions to enable programs to use information about worlds and their objects.

• To define functions, state their uses and give examples

Learning Objectives

• To understand different types of values and give examples • To differentiate the five built-in functions in Alice and how to

use each

• To determine when a collision occurs between objects and how it can be avoided

• To define mathematical expressions and explain why they are needed

(3)

6-1 Functions in Our Lives

In our everyday life, we deal with things according to their functionality. In other words, we define things by what they do. For example, we say that a toaster makes toast, but we do not really indicate how it toasts. We know that a microwave cooks or heats up food, so the functionality of the microwave is to cook food. For all of these devices, we define them by “if I put something in, what I will get out.” Thus, a function gives an output based on the input that we provide.

Other Examples of Functions in Real Life:

• Function to calculate how many hours are in a certain number of days (hours = days * 24)

• Function of monthly income, which depends on the number of working hours and days of work

• Function of the distance a car traveled based on the speed of the car • Function/machine converting a cow into strips of meat

6-2 Functions

Functions are useful programming tools that are used to provide the information required to carry out tasks and calculate a specific value. In Alice, information about worlds and objects (like color, shape and position) is stored in the properties tab. But, what if we need more

(4)

Functions

Statements that are used to ask questions about properties and relationships of objects to one another, or to compute a value.

Each function returns a piece of information, or value.

Where do we get this information?

Alice provides a list of built-in functions associated with the world and objects. We can use functions and properties to allow a program to work with information about a world and its objects.

Think

Functions in Mathematics

A mathematical function relates to an input (from a set of values that it is defined for “Domain”) to an output (from a set of values that the output can admit “Range”) and has only one output for a given input. For example, a function that links a real number with its square f(x)=x^2.

(5)

Values and Types

In our daily conversations, the type of answers (information) we receive is varied according to the kind of the question we ask. For example, the question “how many times we pray each day?” has the numerical value answer of five, and the answer to the question, “are you ten years old?” is Boolean: true or false.

Similarly in Alice, the value of an answer matches the question. For example, the function “boy is within threshold of object” will return a Boolean value. The function “boy distance to” will give the value of the distance in meters. As we will clarify later, you can get the built-in function of a world/object from the tab function in the details area.

Four Common Types of Values in Alice:

1. Number: e.g. 9 or 5. 2. Boolean: e.g. True or False

3. String: e.g. “hello” or “I’m Ahmed” 4. Object: e.g. tree or plane.

Working in Alice: «The boy and the apple tree» Animation

(6)

Identify Objects and Actions

A little boy plays in the park with his cat. Suddenly he feels hungry and

starts looking for food. The boy finds a small apple tree nearby, so he

takes an apple and eats it. Finally, he lays under the tree, next to his cat.

Create a virtual world that includes the following objects:

Local gallery-> Animals-> Cat Local gallery-> People-> Boy

Local gallery-> Ancient-> Apple Tree

Do in Order

Do Together

Boy moves forward 2½ m.

Legs turn forward/backward 1/8 rev. Do Together

Boy moves up 1/4 m.

Arm turns backward 1/2 rev. Do Together

Boy moves down 1/4 m. Apple moves down 1/4 m. Set apple’s vehicle to the boy’s hand Boy’s arm moves toward his mouth

(7)

Implement the previous algorithm in Alice. The “boy and apple tree” program

To view the list of built-in functions for the boy:

1. Select the boy from the object tree.

(8)

The built-in functions in Alice are divided into five sub-categories: 1. Proximity: how close an object is to other object (such as, “Distance to”

and “Distance Above”).

2. Size: like height, weight and depth and how these dimensions are different from those of another object.

3. Spatial Relation: object’s orientation compared to another object (such as, “to the left of” or “to the right of”).

4. Point of View: location of the object in the world.

(9)

We need to move the boy to the tree, but we don’t know exactly how far to move him forward?

Solution 1: use the “trial-and-error” strategy by trying different distances until you find the one that works best. Although this strategy is effective, it is time consuming.

Solution 2: use a function to ask the question, “what is the boy’s distance to the tree?” The answer is the value of the distance in meters the boy will move.

Think

To use the “distance to” function:

1. Drag the boy’s “distance to” function tile into the editor and drop it on top of the “2.5 meter” distance.

2. Select the “apple tree” from the dropdown object list as a target the boy will move to.

(10)

A collision occurs when two objects move to the same location. It happens because the “distance to” is measured from the center of

one object to the center of another.

Discuss with your classmates:

How can a collision be avoided between objects?

---The instruction will read:

Collision

When the program runs, the boy walks right into the middle of the tree! This is called “collision.”

(11)

6-3 Mathematical Expressions

Mathematical expressions are mathematical operations on numbers or other types of values:

• 5+6-(3+7)/2. • (y-7)/(y^2-10).

• 3.75 QR = 1 Riyal + 1 Riyal + 1 Riyal + 50 Dirham + 25 Dirham.

One way to avoid collision is to adjust the distance the boy moves by using an arithmetic expression to subtract the tree’s width from the distance between the two objects.

To accomplish this:

1. Click on the down arrow to the right of the “distance to” tile. 2. Select “math” from menu.

3. Select “boy distance to.” 4. Choose “1.”

The Alice system provides math operators for common math expres-sions including: Addition (+), Subtraction (-), Multiplication (*) and Division (/).

(12)

5. Select the “apple tree” from the object tree, then the functions tab.

6. Drag the “tree’s width” tile and place it in “1” in the command “boy move forward.”

When the program, the boy will move forward so he gets close to the tree without a collision.

To be more technical in avoiding collision, we can use the collision detection formula, which is computed by subtracting half the sum of the boy’s width and the tree’s width from the total distance.

(boy distance to tree - (tree’s width + boy’s width)/2)

Know That

Remember: we must subtract the width of the tree from the distance (not 1), but we had to choose something from the

(13)

Summary of Terms

Functions

Statements that are used to ask questions about properties and relationships of objects to one another or to compute a value.

Values

Pieces of information about a property. Collision

What occurs when two objects move to the same location. Mathematical Expressions

Mathematical operations on numbers or other types of values.

Natasha Scoring a Goal

Create a world as shown below and make Natasha run towards the ball and kick it. The ball should be shot towards the center of the goal and hit the back of the net before stopping.

(14)

Two Cars in the Desert

Create a world as shown below (objects are in the folders Vehicles and Roads and Signs).

Start with the StationWagon (white car) stopped in front of the stop sign and the convertible (red car) coming behind the wagon. The convertible will move until it stops behind the wagon, without colliding into it. After that, the station wagon starts moving and the convertible starts to move behind it.

Nate Organizing the Boxes

Create a scene as in the figure below and let Nate move the crates (in the Things folder) in the room to the corner and stack them above each other to look like the scene on the right.

(15)

1- Answer the Following:

• What are functions? Why they are useful? Give an example of an instance in Alice where functions are useful.

---• In this chapter, we provided a collision detection formula. Write down the formula, and justify how the formula is correct and how it was derived.

---

• We want to make a ball bounce off a building’s wall. What would happen if in Alice we say «ball move forward» without checking for collision? How would you prevent a collision?

---• What is the difference between them? Use an example of an object from Alice to illustrate and explain this difference.

---• Distances in Alice are measured from the --- of an object to --- of another object.

• Tarek was asked to list three functions in real life. What do you think of his answers? Justify why you do or do not agree with Tarek. If the answer is not a real life function, write another one to replace it.

.

1 An app that tracks the number of steps that you have done in a day and returns the value.

---.

2 A function that plays the music in your iPad.

---.

3 Checking out books at a library.

(16)

• For each of the following statements, write down the type of value that would be used to represent it.

.

1 The license plate number of a vehicle.

--- .

2 How many wheels on a car.

--- .

3 Alice was created at Carnegie Mellon University.

--- .

4 The date of Qatar National Day.

--- .

5 The sky is blue.

--- .

6 Which object is the nearest to the sky.

---.

7 Python is a programming language.

--- .

8 The names of your family members.

---

• You are trying to make the scene as shown below, where Alice is going to kick a goal. You add the object «aliceLiddell» from the people folder. Strangely enough, the tab with functions and methods is mixed up!

Classify the following commands as methods or functions, and indicate the function’s return type, Boolean (true/false) or numerical values.

‘is within threshold of object’ ‘distance to’ ‘move at speed’ ‘shorter than’ ‘is to the right of’ ‘say’ ‘walk’ ‘depth’ ‘set pose’

(17)

2- Write an algorithm for each of the following functions and specify the input and the output for each.

Calculating number of egg cartons: this function reads a number of eggs bought by a customer and determines how many cartons of eggs the customer would need. We can fit twelve eggs in one carton.

---• Determining the prime number: This function is given a number and specifies whether or not this number is prime.

---

---• Find the largest number: This function is given three numbers and returns the largest number among them.

---3- Mathematics is an integral part of Computer Science. Explain what similarities you find between functions in mathematics and in Alice.

---4- We introduced the notion of Booleans in this chapter. Find out more about the origin of word “Boolean”. (Hint: associated with the name of a person). Find out about the field of study of this individual, and how it is related to the field of Computer Science.

References

Related documents

As the nature of the present study was to explore neurophysiological effects of tACS, power changes of oscillatory activity as a function of time were calculated for theta

All significant characters traditionally used for discriminating subgenera within Polydrusus (structure and shape of rostrum parts, position and shape of hypostomal-labial

We note also that there are groups, including Aboriginal and Torres Strait Islander women and their children 12 and women and children with disabilities, 13

For instance, probabilistic Horn logic, as originally proposed by Poole in [4], offers a framework that was shown to be as powerful as Bayesian networks, yet it has the advan- tage

 Replace deteriorated shingles or shake in-kind  Consider roof replacement if deterioration is.. substantial

Star scientist authorships of articles as or with employees of a firm were a potent predictor of the eventual success of biotech firms and Zucker, Darby, and Armstrong (2002)

Avaliação dos r esu ltado s Constatar se o apoio disponibilizado é adequado e dirigido à criança; Perceber as vantagens da intervenção para a inclusão no 1º Ciclo

Admiral, Allianz, Aviva, Churchill, Direct Line, Esure, LV=, M&S Insurance, More Than, Quote Me Happy, Tesco Bank and Zurich INSURANCE AGGREGATORS AA, Comparethemarket,