The Math Class. Using various math class methods. Formatting the values.

Similar documents
12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Introduction to Computer Science Unit 2. Notes

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

Introduction to Computer Science Unit 2. Notes

Computer Programming I - Unit 2 Lecture 1 of 13

CS110: PROGRAMMING LANGUAGE I

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

Chapter 5 Methods / Functions

Methods: A Deeper Look

AP CS Unit 3: Control Structures Notes

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

CT 229 Java Syntax Continued

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

AP Computer Science A. Return values


Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Lecture 6: While Loops and the Math Class

Downloaded from Chapter 2. Functions

Advanced features of the Calculate signal tool

Review for Test 1 (Chapter 1-5)

CS177 Python Programming. Recitation 2 - Computing with Numbers

Functions, Randomness and Libraries

Pace University. Fundamental Concepts of CS121 1

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Building Java Programs

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Formatting Output & Enumerated Types & Wrapper Classes

Object-Based Programming. Programming with Objects

Using Free Functions

Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 6 Methods. Dr. Hikmat Jaber

Variables, Types, Operations on Numbers

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Introduction to Computer Science and Object-Oriented Programming

AP Programming - Chapter 3 Lecture. An Introduction

1001ICT Introduction To Programming Lecture Notes

C Functions. 5.2 Program Modules in C

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Building Java Programs

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

What did we talk about last time? Examples switch statements

Building Java Programs

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Important Java terminology

Function I/O. Function Input and Output. Input through actual parameters. Output through return value. Input/Output through side effects

Function I/O. Last Updated 10/30/18

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

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

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

Introduction to Programming

Sta$cs and forma.ng numbers

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CIS133J. Working with Numbers in Java

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Building Java Programs

Using Java Classes Fall 2018 Margaret Reid-Miller

Advanced Object Concepts

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

Coding in JavaScript functions

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Outline. Data and Operations. Data Types. Integral Types

Building Java Programs

Functions. Systems Programming Concepts

Module 4: Characters, Strings, and Mathematical Functions

Excel Functions INTRODUCTION COUNT AND COUNTIF FUNCTIONS

Getting started with Java

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

Topic 12 more if/else, cumulative algorithms, printf

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

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

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

CS Programming I: Primitives and Expressions

M e t h o d s a n d P a r a m e t e r s

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

Building Java Programs

Methods CSC 121 Spring 2017 Howard Rosenthal

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

CS177 Python Programming. Recita4on 2 - Compu4ng with Numbers

Chapter 3 - Functions

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

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

CS 61B Data Structures and Programming Methodology. June David Sun

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Section 2.2 Your First Program in Java: Printing a Line of Text

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

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Transcription:

The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class, there is no need to import the class because it is automatically imported (by the java.lang package). The functions covered are the following: Method Description static double pow (double y, double x) Returns y raised to the x static double sqrt (double arg) Returns the square root of arg static int abs (int arg) Returns the absolute value of arg static double ceil (double arg) Returns the smallest whole number greater than or equal to arg static double floor (double arg) Returns the largest whole number less than or equal to arg static int round (float arg) Returns arg rounded up to the nearest int static long round (double arg) Returns arg rounded up to the nearest long static double random() Returns a random number between 0 and 1 The class name Math must be included each time the method is used. For instance: System.out.println(Math.pow(2,8)); The Math class Function Name Arguments Ms.P.Sullivan Page 1 of 6

In the previous example the Math class is being called and the pow method is called with the arguments of 2 and 8. This means that 2 to the power of 8 is worked out which will result in 256. If the result must be stored in a variable the statement can be changed to double result = Math.pow(2,8); Having to use the class name Math every time a function is required might be tedious, so it can be avoided by using the static import statement at the beginning (before the class declaration) import static.java.lang.math.*; and then the statement can be coded as double result = pow(2,8); So, you can choose whichever method you prefer, either use the import at the beginning or add the class name Math to each method you re using. Math.pow() import static java.lang.math.*; class Power { public static void main (String args[]){ int a = 5; int b = 6; System.out.println(pow(a,b)); This program will work out 5 to the power of 6 and it will display 15625. Math.sqrt() import static java.lang.math.*; class SquareRoot { public static void main (String args[]){ int a = 100; System.out.println(sqrt(a)); The above program will work out the square root of 100 and so it will result in 10. Ms.P.Sullivan Page 2 of 6

Maths.abs() The absolute value of a number is equal to the same number without the sign. It can be useful on calculations which require positive numbers only; for instance finding the square root of a negative number cannot be done, so first you work out the absolute value. import static java.lang.math.*; class SquareRoot { public static void main (String args[]){ double a = -5.4; System.out.println(abs(a)); This program will return the value of 5.4 since the negative symbol is dropped. Math.random() A random number is a computer generated number picked up from a set of numbers. random() returns a double number ranging from.00000 0 to.99999 9. This can be ideal if randomly generated numbers are required, such as rolling a dice or picking a number for the lotto. For instance, to generate a random number from 0 to 9 (inclusive) the following code can be used: int num = (int)(math.random() * 10); if the number required must be from 1 to 10, +1 must be added at the end. int num = (int)(math.random() * 10)+1; The Math.random() method returns a double number so the it must be type casted into an integer number by using (int). Randomly generated numbers start from 0, so if these must be started from 1, a +1 must be added at the end. For instance to generate a random number from 1 to 6, like a dice this code is required: int die = (int)(math.random()*6)+1; This will generate a random number from 1 to 6. Ms.P.Sullivan Page 3 of 6

Math.round() This method returns the closest value to the integer value of the number. If the fraction value is equal to or more than 0.5, it will add 1 to the original value. Math.round() will remove the fraction and just return the rounded whole number. It can accept a double value and return a long, or accept a float value and return an integer. For example double num1 = Math.round(1234.54543423232); will return 1235, whilst double num1 = Math.round(1234.44543423232); will return 1234. Math.ceil() This will return the smallest integer number which is not less than the supplied number. Method Result Math.ceil(11); 11 Math.ceil(11.3); 12 Math.ceil(-13.4); -13 Math.floor() This will return the largest integer number which is not greater than the supplied number. Method Result Math.floor(11); 11 Math.floor(11.3); 11 Math.floor(-13.4); -14 Ms.P.Sullivan Page 4 of 6

Formatting values printf() To format text a specified number of decimal places printf() can be used instead of println(). When using printf(), the placeholders must be specified inside the message (inside the quotes), followed by the variable. For instance: int num = 5; System.out.printf( %d\n,num); In this case what happens is 5 will be displayed on a line, then the cursor will move to the next line. This happens because the %d is replaced with the value of num and then the escape character \n is applied. There are different placeholders for different data types: Placeholder Used for %d int, byte, short, long %f float %s String %c char When using %f the number of decimal places can be specified as well. For instance: System.out.printf( Formatted to 2 decimal places :%.2f\n,ans); A field can also be used to hold a number. In this example a field of size 10 is created to display the number: System.out.printf( Formatted to 2 decimal places :%10.2f\n,ans); Finally, if the empty spaces are to filled in with zeros it can be coded as: System.out.printf( Formatted to 2 decimal places :%010.2f\n,ans); Ms.P.Sullivan Page 5 of 6

Activities 1. Develop an application naming it PowerOf to ask the user to input a number between 2 and 10 and then output: a. The number inputted to the power of 3 b. The number inputted to the power of 5 2. Write an application named FindSquareRt to output the square root of +144 and also the square root of -25. (Note: you have to use abs() in the case of -25. Why?) 3. Create an application to simulate the Super Five lottery. That is you need to generate one number between 1 and 43. 4. Lotto draws can generate a number between 1 and 90. Create an application that generates one number for the lotto draw. 5. Create a class naming it MyRound to round and output the following values to integers: a. 24.244 b. 24.566 c. 24.999 *** Ms.P.Sullivan Page 6 of 6