Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Similar documents
Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

C Functions. 5.2 Program Modules in C

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

ANSI C Programming Simple Programs

ECET 264 C Programming Language with Applications

Computer Science & Engineering 150A Problem Solving Using Computers

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Functions. Systems Programming Concepts

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

C++ Programming Lecture 11 Functions Part I

Chapter 2. Outline. Simple C++ Programs

Chapter 4: Basic C Operators

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

C Programs: Simple Statements and Expressions

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Beginning C Programming for Engineers

FAQ No. 53. ihost: Logic Points. Roles and Privileges. Adding and removing logic points. Accessing and using the Logic Editor

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Floating Point Arithmetic

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Python Programming: An Introduction to Computer Science

Fundamentals of Programming & Procedural Programming

CSE123. Program Design and Modular Programming Functions 1-1

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

C Program Structures

CT 229 Java Syntax Continued

1001ICT Introduction To Programming Lecture Notes

Roundoff Errors and Computer Arithmetic

Engineering Problem Solving with C++, Etter/Ingber

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Script started on Thu 25 Aug :00:40 PM CDT

COMP2611: Computer Organization. Data Representation

MAT128A: Numerical Analysis Lecture Two: Finite Precision Arithmetic

Up next. Midterm. Today s lecture. To follow

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Programming in MATLAB

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Floating Point January 24, 2008

Java Classes: Math, Integer A C S L E C T U R E 8

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

XQ: An XML Query Language Language Reference Manual

Using the um-fpu with the Javelin Stamp

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Standard Library Functions Outline

Expressions. Eric McCreath

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Dr Richard Greenaway

Data Representation Floating Point

Number Systems. Both numbers are positive

Floating Point Numbers

C++ Programming: From Problem Analysis to Program Design, Third Edition

Floating Point. CSE 351 Autumn Instructor: Justin Hsia

FLOATING POINT NUMBERS

2 Computation with Floating-Point Numbers

Julia Calculator ( Introduction)

Using Free Functions

Chapter 2. Data Representation in Computer Systems

CS3157: Advanced Programming. Outline

Methods: A Deeper Look

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Mentor Graphics Predefined Packages

C++ Overview. Chapter 1. Chapter 2

Built-in Types of Data

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

CHAPTER 3 Expressions, Functions, Output

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754

Floating-Point Data Representation and Manipulation 198:231 Introduction to Computer Organization Lecture 3

Functions and Recursion

System Programming CISC 360. Floating Point September 16, 2008

Systems I. Floating Point. Topics IEEE Floating Point Standard Rounding Floating Point Operations Mathematical properties

1.2 Round-off Errors and Computer Arithmetic

Floating Point Representation in Computers

Floating Point Arithmetic

Floating Point Puzzles The course that gives CMU its Zip! Floating Point Jan 22, IEEE Floating Point. Fractional Binary Numbers.

CS429: Computer Organization and Architecture

Chapter 2 Float Point Arithmetic. Real Numbers in Decimal Notation. Real Numbers in Decimal Notation

Lecture 2 FORTRAN Basics. Lubna Ahmed

2 Computation with Floating-Point Numbers

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Foundations of Computer Systems

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Floating Point. CSE 351 Autumn Instructor: Justin Hsia

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000.

Introduction to C Language

Floating Point. CSE 351 Autumn Instructor: Justin Hsia

Math 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Floating-point representations

Floating-point representations

Goals for This Lecture:

Binary floating point encodings

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Transcription:

Lecture 14 Math in C Daily Puzzle Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Daily Puzzle SOLUTION Eleven plus two = twelve plus one Announcements Practice, practice, and practice even more.

Floating-point arithmetic Precision and speed. A variable of type double has about twice the precision of a normal float variable. Does double-precision arithmetic take longer? C requires all arithmetic done in double. What s the difference? Suppose you are computing π 100. The influence of the number of significant digits used for π is the following. Using five significant digits for π gives (3.1416) 100 = 5.189061599 * 10 49 while using eight significant digits for π gives (3.1415926) 100 = 5.1897839464 * 10 49

What s the difference? The first estimate of π has five significant digits; however (3.1416) 100 is accurate only for the first three digits. Accuracy is reduced after numerous arithmetic operations. Numerical inaccuracies One of the problems with floating point types is that sometimes errors occur in representing real numbers.

Numerical inaccuracies In the binary number system, the only numbers which can be represented exactly are those numbers whose denominators contain only factors of two (2): e.g. 1/2 = 0.1 1/4 = 0.01 3/8 = 0.011 11/16 = 0.1011, etc. Round-off errors Sometimes an error occurs in representing real numbers. Certain fractions cannot be represented exactly in decimal notation e.g. 1/3 0.33333

Round-off errors This is called representational or round-off error. It depends on the number of bits used in the mantissa 0.1 has a representational error as a double value Approximated to.099999 9 or.1000000 1 Why round-off occurs Floating-point arithmetic is not exact. Did you know that ⅓+⅓ ⅔ ⅔ as floating-point is 6.667e-1 ⅓ as floating-point is 3.333e-1 ⅓ + ⅓ = 3.333e-1+3.333e-1=6.666e-1 6.666e-1 is not 6.667e-1

Accuracy How many digits of the fraction are accurate? The accuracy depends on the calculation. Certain operations, like subtracting two numbers that are close, generate inexact results. Accuracy e.g. The correct answer is 0.000e+0.

Accuracy Looking at it in binary: 0.3 10 =? 2 = 0.01001 1001 1001. 2 = 0.2999999 10 Avoid round-off error Use double instead of float. This solution provides approximately twice the accuracy, as well as a greater range.

Cancellation error Other problems occur when manipulating very small and very large numbers. Cancellation error is an error resulting from applying an arithmetic operation to operands of vastly different magnitudes. Cancellation error For example, adding e.g. 1000.0 + 0.000001234 = 1000.0

Underflow Arithmetic underflow occurs when a very small computational result is represented as zero e.g. 0.00007 0.000005 = 0 Overflow Arithmetic overflow is an error which results from an attempt to represent a computational result that is too large e.g. 4000 4000 (short) = 16,000,000 32,767 is the max for type int! Results are compiler / machine / OS dependent.

Not a what? NaN = Not-a-Number An IEEE floating point representation for the result of a numerical operation which cannot return a valid number value. A NaN can result from multiplying an infinity by a zero, or from subtracting one infinity from another Math functions The C math library has the header file math.h, and contains the following useful functions:

Math functions acos(d) arc cosine of d asin(d) arc sine of d atan(d) arc tangent of d atan2(d1,d2) arc tangent of d1/d2 cbrt(d) cube root of d cos(d) cosine of d cosh(d) hyperbolic cosine of d exp(d) exponential of d fabs(d) absolute value of d hypot(d1,d2) sqrt(d1 * d1 + d2 * d2) log(d) natural logarithm of d Math functions log10(d) pow(d1,d2) sin(d) sinh(d) sqrt(d) tan(d) tanh(d) logarithm (base 10) of d d1 raised to the power d2 sine of d hyperbolic sine of d square root of d tangent of d hyperbolic tangent of d NOTE: Trigonometric functions use radians.

Math functions A program that makes use of the C math library would contain the statement #include <math.h> close to its start. And is compiled using the -lm (-ell emm) directive. Math functions In the body of the program, a statement like x = cos(y); would cause the variable x to be assigned a value which is the cosine of the value of the variable y (both x and y should be of type double).

Ka - pow!! Exponentiation in C is performed by the library function pow: z = pow(x,y); would cause the variable z to be assigned a value which is x raised to the power of y. Note: x 2 is best represented as x * x How many logs? Don t get the log functions confused: The natural logarithm, usually represented by ln is represented in C by: z = log(x);

e eh? Also the function e x where e is the base for natural logarithms, or approximately 2.718282. It is represented in C by: z = exp(x); Math constants The C math library comes with a useful set of predefined mathematical constants: M_PI Pi M_PI_2 Pi divided by two M_PI_4 Pi divided by four M_1_PI The reciprocal of pi (1/pi) M_SQRT2 The square root of two M_SQRT1_2 The reciprocal of the square root of two M_E The base of natural logarithms

Number conversion There are several cases in which data of one numeric type is automatically converted to another numeric type: arithmetic conversion. Automatic arithmetic conversions occur when an expression is being evaluated. Number conversion For example that i is an int and p is a double. In the expression i + p the variable i is promoted to a double and the expression i + p as a whole has type double.

Number conversion This process of conversion has various names: automatic conversion implicit conversion coercion promotion widening Implicit conversion An automatic conversion can occur in an expression with different numeric types. int k = 5; double x = 1.5; The value of k + x is 6.5 Value of int variable k is converted to type double before the expression is evaluated.

Implicit conversion An automatic conversion can occur across an assignment. For example: int i; double d; d = i; causes the value of i, to be converted to a double and then assigned to d; double is the type of the expression as a whole. Implicit conversion A promotion such as d = i is usually well behaved. A demotion such as i = d can lose information. Here, the fractional part of d is discarded.

Implicit conversion An automatic conversion can occur within an assignment statement. int k = 5, m = 4; double z; z = k / m; The value of k / m is 1; the value assigned to z is 1.0. Implicit conversion The expression is evaluated first. The result is then converted to type double for assignment.

Implicit conversion An automatic conversion can occur within an assignment statement. int n; double x = 1.5, y = 2.1; n = x * y; The value of x * y is 3.15; the value assigned to n is 3. Number conversion The expression is evaluated first. The result is then converted to type int for assignment, and the fractional part is lost.

Explicit conversion The value of an expression can be converted to a different data type by prepending the name of the desired data type, enclosed in parenthesis. Explicit conversion This type of conversion is known as a cast, and has the following general form: (type) variable This causes the value to be converted before it is used in computation.

Explicit conversion Thus, to convert the value stored in an int variable j into a double value: int j; double k; k = (double) j; Explicit conversion To avoid mixing data types when dividing a double variable x by an int variable i: int i; double x, y; y = x / (double) i;

Explicit conversion What would be the result of the following expression, where both variables n and d are of type int? (double) (n / d) Explicit conversion The quotient (n / d) is calculated first, resulting in the loss of the fractional part. The cast double simply converts this whole number to type double. Better to use: (double)n /(double)d

Explicit conversion For example: (int)65.59834 == 65 (double)(10.0/4.0) == 2.5 (double)10/(double)4 == 2.5 (double)10/4 == 2.5 10/(double)4 == 2.5 (double)(10/4) == 2 Mixed calculations Even though d_minutes is declared as a double, the result is an int always equal to the value of min. int min, sec; double d_minutes; d_minutes = min + sec/60; Why?

Mixed calculations Because sec/60 is an integer calculation which always produces a value of 0 unless sec equals exactly 60. The correct answer can be obtained by: sec/60.0 It forces C to perform floating-point arithmetic. Special math Apart from the standard functions found in the C math library (math.h), there are also a number of more specialised functions.

ceil The function ceil(x) returns the smallest whole number not less than x: x = 5.7 z = ceil(x); would cause the variable z to be assigned a value which is the ceiling of x, i.e. z = 6.0. floor The function floor(x) returns the largest whole number not greater than x: x = 5.7 z = floor(x); would cause the variable z to be assigned a value which is the floor of x, i.e. z = 5.0.

modf The function modf(x,&i) breaks x into integer and fractional parts: x = 5.7 z = modf(x,&i); would cause the variable z to be assigned the value f and indirectly the value i, so that: x = i + f, hence, z = 5.0, and i =0.7 Randomness What is randomness?

Randomness The building blocks of cryptography. A sequence is considered random if no patterns can be recognized in it - the longer the string, the stronger the encryption.

Randomness A large class of scientific calculations require the use of random variables. Online gambling sites, games. Random numbers There are no such things as random numbers on computers. Computers are physically incapable of randomness. The world is random. Computers aren t.

Random numbers All generate numbers are pseudo-random numbers. Fake random number generators are called Pseudo-Random Number Generators (PRNG) Random numbers Unless you have a fancy device that generates a random number using a nuclear decay radiation source.

Random numbers Some people have used lava lamps to generate random numbers. Lavarand (patented 1996). Random numbers A call to the rand() function (header file stdlib.h), with no arguments, returns a fairly good approximation to a random integer in the range 0 to RAND_MAX (defined in stdlib.h).

Random numbers int i, randomnum; for (i=0; i<100; i=i+1) { randomnum = rand(); printf( %d, randomnum); } Seeding Results are identical if used more than once. That is because the initial seed used is identical each time. The seed is used to trigger the sequence of random numbers. Seeding the generator in this manner ensures that a different set of random numbers is generated automatically each time the program is run.

srand() is used to seed a new sequence of numbers to be returned by rand(). Seeding time() function from the library time.h int i, randomnum; srand(time(0)); the number of seconds elapsed since 00:00:00 UTC, January 1st, 1970. for (i=0; i<100; i=i+1) { randomnum = rand(); printf( %d, randomnum); } Real random numbers Real random numbers are generated by dividing the random number obtained by RAND_MAX.

Real random numbers int i, randomnum; double drand; srand(time(0)); for (i=0; i<100; i=i+1) { randomnum = rand(); drand = randomnum / (double) RAND_MAX; printf( %f, drand); } Functions?

Functions? Functions?

Functions? double SQRT(double number) { double tolerance, newx, x; int count, true=1; tolerance = 0.0000001; count = 0; x = 1; do { count = count + 1; newx = 0.5 * (x + number / x); if (FABS(x - newx) < tolerance) break; x = newx; } while (true); } return newx;