A First Course in Scientific Computing Fortran Version

Total Page:16

File Type:pdf, Size:1020Kb

A First Course in Scientific Computing Fortran Version A First Course in Scientific Computing Symbolic, Graphic, and Numeric Modeling Using Maple, Java, Mathematica, and Fortran90 Fortran Version RUBIN H. LANDAU Fortran Coauthors: KYLE AUGUSTSON SALLY D. HAERER PRINCETON UNIVERSITY PRESS PRINCETON AND OXFORD ii Copyright c 2005 by Princeton University Press 41 William Street, Princeton, New Jersey 08540 3 Market Place, Woodstock, Oxfordshire OX20 1SY All Rights Reserved Contents Preface xiii Chapter 1. Introduction 1 1.1 Nature of Scientific Computing 1 1.2 Talking to Computers 2 1.3 Instructional Guide 4 1.4 Exercises to Come Back To 6 PART 1. MAPLE OR MATHEMATICA BY DOING (SEE TEXT OR CD) 9 PART 2. FORTRAN BY DOING 195 Chapter 9. Getting Started with Fortran 197 9.1 Another Way to Talk to a Computer 197 9.2 Fortran Program Pieces 199 9.3 Entering and Running Your First Program 201 9.4 Looking Inside Area.f90 203 9.5 Key Words 205 9.6 Supplementary Exercises 206 Chapter 10. Data Types, Limits, Procedures; Rocket Golf 207 10.1 Problem and Theory (same as Chapter 3) 207 10.2 Fortran’s Primitive Data Types 207 10.3 Integers 208 10.4 Floating-Point Numbers 210 10.5 Machine Precision 211 10.6 Under- and Overflows 211 Numerical Constants 212 10.7 Experiment: Determine Your Machine’s Precision 212 10.8 Naming Conventions 214 iv CONTENTS 10.9 Mathematical (Intrinsic) Functions 215 10.10 User-Defined Procedures: Functions and Subroutines 216 Functions 217 Subroutines 218 10.11 Solution: Viewing Rocket Golf 220 Assessment 224 10.12 Your Problem: Modify Golf.f90 225 10.13 Key Words 226 10.14 Further Exercises 226 Chapter 11. Visualization with Fortran 228 11.1 An Overview of Dislin 228 2-D Graphs within Fortran using Dislin 229 Running the Sample Program 231 Dislin Matrix Plots 233 Dislin Surface Plots 234 11.2 Setting up Dislin * 236 11.3 Gnuplot Basics 238 Printing Plots 240 Gnuplot Surface (3-D) Plots 241 Chapter 12. Flow Control via Logic; Projectiles 243 12.1 Problem: Frictionless Projectile Motion 243 12.2 Theory: Kinematics 244 12.3 Computer Science: Designing Structured Programs 245 Flow Charts and Pseudocode 246 12.4 Flow Control via Logic 247 Conditional and Relational Operators 248 Control Structures 249 Select Case 253 12.5 Implementation: projectile.f90 254 12.6 Solution: Projectile Trajectories 254 12.7 Key Words 255 12.8 Supplementary Exercises 255 Chapter 13. Fortran Input and Output 257 13.1 Basic I/O 258 13.2 Formatted Output 259 13.3 File I/O 260 Chapter 14. Numerical Integration; Power and Energy Usage 262 14.1 Problem (Same as Chapter 6): Power and Energy 262 14.2 Algorithms: Trapezoid and Simpson’s Rules 263 Trapezoid Rule 264 CONTENTS v 14.3 Implementation: Trap.f90 266 Implementation with Nested Loops 266 Improved Method: Simpson’s Rule 267 14.4 Assessment: Which Rule Is Better? 268 14.5 Key Words and Concepts 269 14.6 Supplementary Exercises 269 Chapter 15. Differential Equations with Maple and Fortran* 271 15.1 Problem: Projectile Motion with Drag 271 15.2 Model: Velocity-Dependent Drag 272 15.3 Algorithm: Numerical Differentiation 273 15.4 Math: Solving Differential Equations 273 Implementation: ProjectileAir.f90 275 15.5 Assessment: Balls Falling Out of the Sky? 275 Improved Algorithm: Verlet* 277 15.6 Maple: Differential-Equation Tools 278 Extract Right-Hand Side: rhs 280 Second-Order ODE with Plot 280 System of ODEs 281 15.7 Maple Solution: Drag ∝ Velocity 282 15.8 Extract Operands 284 Solution for R and T 285 2 15.9 Drag ∝ v (Exercise) 286 3 2 15.10 Drag ∝ v / 287 Defining Functions from Procedures 289 15.11 Exploration: Planetary Motion* 290 Implementation: Planet.java* 291 15.12 Key Words 291 15.13 Supplementary Exercises 292 Chapter 16. Object-Oriented Programming; Complex Currents 293 16.1 Problem: Resonance in RLC Circuit 293 16.2 Math: Complex Numbers 293 Complex Arithmetic Review 296 16.3 Theory: Resistance Becomes Impedance 297 Solution for Complex Current 298 16.4 CS: Abstract Data Types, Objects 299 16.5 Objects in Fortran 301 Data by Reference 301 Sample Data Type 301 Object Constructors 305 Declaring and Creating Objects 305 Instances 306 16.6 Fortran Solution: Complex Currents 306 vi CONTENTS 16.7 Maple Solution: Complex Currents 307 Maple’s Surface Plots of Complex Impedance 309 16.8 Key Words 311 16.9 Fortran and Maple Exercises 311 Chapter 17. Arrays: Vectors, Matrices; Rigid-Body Rotations 312 17.1 Problem: Rigid-Body Rotations 312 17.2 Theory: Angular-Momentum Dynamics 314 17.3 Computer Science and Math: Arrays vs. Vectors and Matrices 315 17.4 Array Declaration and Instantiation 316 Array Sizes 318 Fixed-Sized Arrays 318 Assumed-Shape Arrays* 319 Allocatable Arrays* 319 17.5 Arrays as Arguments to Procedures* 321 Computation: Changing Array Arguments in Functions 322 17.6 Application to Rotations 324 17.7 Key Words 325 17.8 Supplementary Exercises 325 Chapter 18. Advanced Function Methods, Objects 329 18.1 Procedure Modules and Interfaces 329 18.2 Changing the Arguments of a Function 332 18.3 Functions Calling Functions 334 18.4 Function Overloading 335 Chapter 19. Discrete Math, Arrays as Bins; Bug Dynamics* 337 19.1 Problem: Variability of Bug Populations 337 19.2 Theory: Self-Limiting Growth, Discrete Maps 337 19.3 Assessment: Properties of Nonlinear Maps 339 19.4 Exploration: Bifurcation Diagram, Bugs.f90* 340 Implementation; Bifurcation Diagram 341 Binning 342 19.5 Exploration: Other Discrete Maps* 343 Chapter 20. 2-D Arrays: File I/O, PDE’s; Realistic Capacitor 344 20.1 Problem: Field of Realistic Capacitor 344 20.2 Theory and Model: Electrostatics and PDEs 344 Laplace’s Partial Differential Equation* 346 20.3 Algorithm: Finite Differences 346 20.4 Implementation: LaplaceFile.f90 348 LaplaceFile.f90 Orientation and Visualization 349 20.5 Exploration 350 CONTENTS vii 20.6 Exploration: 3-D Capacitor* 352 20.7 Key Words 352 Chapter 21. Web Computing (see Java Version) 353 PART 3. LATEX SURVIVAL GUIDE 355 Chapter 22. LATEX for Text 357 22.1 Why LATEX? 357 22.2 Structure of a LATEX Document 358 22.3 Sample Input File (Sample.tex) 358 22.4 Sample LATEX Output 360 Brief Look at Input File 361 Special Characters 361 Paragraphs, Spaces, and Breaks 362 Quotation Marks and Dashes 363 22.5 Fonts for Text 364 Type Sizes 365 Fancy Text Accents 365 Math Symbols in Text 365 22.6 Environments 366 22.7 Lists 366 Text Tables 367 Floating Tables 368 22.8 Sections 369 Subsections 369 Quotations and Footnotes 370 Chapter 23. LATEX for Mathematics 371 23.1 Entering Mathematics: Math Mode 371 23.2 Mathematical Symbols and Greek 372 Greek Letters 372 Relations 373 Negative Relations 373 Binary (and Other) Operators 374 Arrows 374 Math Parentheses 374 Miscellaneous Math Symbols 374 “Big” Operators 375 23.3 Math Accents 375 23.4 Superscripts and Subscripts 375 23.5 Calculus and Sums 375 23.6 Changing Math Fonts 376 viii CONTENTS 23.7 Math Functions 376 23.8 Fractions 376 23.9 Roots 377 23.10 Brackets (Delimiters) 377 23.11 Multiline Equations 378 23.12 Matrices and Math Arrays 379 23.13 Including Graphics 380 23.14 Exercise: Putting It All Together 382 Appendix A. Glossary 386 Appendix B. Fortran Quick Reference 395 B.1 Transferring Files from the CD 398 B.2 Using our Fortran Programs 399 Bibliography 400 Index 405 List of Figures 1.1 Left: Computational science is a multidisciplinary field that combines science with computer science and mathematics. Right: A new paradigm for science in which simulation plays as es- sential a role as does experiment and theory. 2 1.2 A schematic view of a computer’s kernel and shells. 3 9.1 Steps in compiling and executing. 199 10.1 A schematic representation of the limits of single-precision floating-point numbers, and the consequences of exceeding those limits. 210 10.2 Left: The structure of a Fortran program with no procedures. Right: The structure of a Fortran program with a main pro- gram, a subroutine, and a function. The main program and the two procedures are contained in the same source file, for instance, ProgName.f90. 216 10.3 A plot of the function γ(v) output from the program Golf.f90. Compare to similar plot done with Maple in Chap. 3. 223 11.1 The Dislin output from the program EasyDislinPlot.f90. 231 11.2 The Dislin output from the program MatrixPlot.f90. 234 11.3 The Dislin output from the program Laplace.f90. 237 11.4 A gnuplot graph for three data sets with impulses and lines. 239 11.5 Gnuplot’s surface plot of a scattering amplitude ImT as a func- tion of complex energy E. 240 12.1 Left: The trajectory of a projectile fired with initial velocity V0 in the θ direction. The nonparabolic curve includes air re- sistance. Right: The components of the initial velocity V0 projected onto the x and y axes. 243 12.2 A flow chart illustrating a possible program to compute pro- jectile motion. On the left, we show the very high-level basic components of the program, while on the right, we show some of the details of the logic flow structures. 246 x LIST OF FIGURES 12.3 Left: Sequential or linear programming. Right: The if-then- else structure, one of several structures used to write nonlinear program segments based on logical decisions. 247 12.4 Left: The Fortran Do-loop iteration. Right: The Fortran Do- while loop uses a general test, in contrast to the Do-loop’s iter- ation count.
Recommended publications
  • Create a Program Which Will Accept the Price of a Number of Items. • You Must State the Number of Items in the Basket
    PROBLEM: Create a program which will accept the price of a number of items. • You must state the number of items in the basket. • The program will then accept the unit price and the quantity for each item. • It must then calculate the item prices and the total price. • The program must also calculate and add a 5% tax. • If the total price exceeds $450, a discount of $15 is given to the customer; else he/she pays the full amount. • Display the total price, tax, discounted total if applicable, as well as the total number of items bought. • A thank you message must appear at the bottom. SOLUTION First establish your inputs and your outputs, and then develop your IPO chart. Remember: this phase is called - Analysis Of The Problem. So what are your inputs & output? : Variable names: Number of items (input & output) Num (Assume there are 4 items) Unit price of each item (input) Price1, Price2, Price3, Price4 Quantity of each item (Input) Quan1, Quan2, Quan3, Quan4 Total price (output) TotPrice Tax amount (output) Tax Discounted total price (output) DiscTotPrice In your IPO chart, you will describe the logical steps to move from your inputs to your outputs. INPUT PROCESSING OUTPUT Price1, Price2, 1. Get the number of items TotPrice, Tax, Price3, Price4, 2. Get the price and quantity of the each item DiscTaxedTotal, Num 3. Calculate a sub-total for each item TaxedTotal Quan1, Quan2, 4. Calculate the overall total Num Quan3, Quan4 5. Calculate the tax payable {5% of total} 6. If TaxedTotal > 450 then Apply discount {Total minus 15} Display: TotPrice, Tax, DiscTaxedTotal, TaxedTotal, Num Else TaxedTotal is paid Display: TotPrice, Tax, TaxedTotal, Num Note that there are some variables that are neither input nor output.
    [Show full text]
  • TI 83/84: Scientific Notation on Your Calculator
    TI 83/84: Scientific Notation on your calculator this is above the comma, next to the square root! choose the proper MODE : Normal or Sci entering numbers: 2.39 x 106 on calculator: 2.39 2nd EE 6 ENTER reading numbers: 2.39E6 on the calculator means for us. • When you're in Normal mode, the calculator will write regular numbers unless they get too big or too small, when it will switch to scientific notation. • In Sci mode, the calculator displays every answer as scientific notation. • In both modes, you can type in numbers in scientific notation or as regular numbers. Humans should never, ever, ever write scientific notation using the calculator’s E notation! Try these problems. Answer in scientific notation, and round decimals to two places. 2.39 x 1016 (5) 2.39 x 109+ 4.7 x 10 10 (4) 4.7 x 10−3 3.01 103 1.07 10 0 2.39 10 5 4.94 10 10 5.09 1018 − 3.76 10−− 1 2.39 10 5 7.93 10 8 Remember to change your MODE back to Normal when you're done. Using the STORE key: Let's say that you want to store a number so that you can use it later, or that you want to store answers for several different variables, and then use them together in one problem. Here's how: Enter the number, then press STO (above the ON key), then press ALPHA and the letter you want. (The letters are in alphabetical order above the other keys.) Then press ENTER.
    [Show full text]
  • Texworks: Lowering the Barrier to Entry
    TEXworks: Lowering the barrier to entry Jonathan Kew 21 Ireton Court Thame OX9 3EB England [email protected] 1 Introduction The standard TEXworks workflow will also be PDF-centric, using pdfT X and X T X as typeset- One of the most successful TEX interfaces in recent E E E years has been Dick Koch's award-winning TeXShop ting engines and generating PDF documents as the on Mac OS X. I believe a large part of its success has default formatted output. Although it will still be been due to its relative simplicity, which has invited possible to configure a processing path based on new users to begin working with the system with- DVI, newcomers to the TEX world need not be con- out baffling them with options or cluttering their cerned with DVI at all, but can generally treat TEX screen with controls and buttons they don't under- as a system that goes directly from marked-up text stand. Experienced users may prefer environments files to ready-to-use PDF documents. T Xworks includes an integrated PDF viewer, such as iTEXMac, AUCTEX (or on other platforms, E based on the Poppler library, so there is no need WinEDT, Kile, TEXmaker, or many others), with more advanced editing features and project man- to switch to an external program such as Acrobat, agement, but the simplicity of the TeXShop model xpdf, etc., to view the typeset output. The inte- has much to recommend it for the new or occasional grated viewer also allows it to support source $ user.
    [Show full text]
  • Primitive Number Types
    Primitive number types Values of each of the primitive number types Java has these 4 primitive integral types: byte: A value occupies 1 byte (8 bits). The range of values is -2^7..2^7-1, or -128..127 short: A value occupies 2 bytes (16 bits). The range of values is -2^15..2^15-1 int: A value occupies 4 bytes (32 bits). The range of values is -2^31..2^31-1 long: A value occupies 8 bytes (64 bits). The range of values is -2^63..2^63-1 and two “floating-point” types, whose values are approximations to the real numbers: float: A value occupies 4 bytes (32 bits). double: A value occupies 8 bytes (64 bits). Values of the integral types are maintained in two’s complement notation (see the dictionary entry for two’s complement notation). A discussion of floating-point values is outside the scope of this website, except to say that some bits are used for the mantissa and some for the exponent and that infinity and NaN (not a number) are both floating-point values. We don’t discuss this further. Generally, one uses mainly types int and double. But if you are declaring a large array and you know that the values fit in a byte, you can save ¾ of the space using a byte array instead of an int array, e.g. byte[] b= new byte[1000]; Operations on the primitive integer types Types byte and short have no operations. Instead, operations on their values int and long operations are treated as if the values were of type int.
    [Show full text]
  • Fortran Resources 1
    Fortran Resources 1 Ian D Chivers Jane Sleightholme May 7, 2021 1The original basis for this document was Mike Metcalf’s Fortran Information File. The next input came from people on comp-fortran-90. Details of how to subscribe or browse this list can be found in this document. If you have any corrections, additions, suggestions etc to make please contact us and we will endeavor to include your comments in later versions. Thanks to all the people who have contributed. Revision history The most recent version can be found at https://www.fortranplus.co.uk/fortran-information/ and the files section of the comp-fortran-90 list. https://www.jiscmail.ac.uk/cgi-bin/webadmin?A0=comp-fortran-90 • May 2021. Major update to the Intel entry. Also changes to the editors and IDE section, the graphics section, and the parallel programming section. • October 2020. Added an entry for Nvidia to the compiler section. Nvidia has integrated the PGI compiler suite into their NVIDIA HPC SDK product. Nvidia are also contributing to the LLVM Flang project. Updated the ’Additional Compiler Information’ entry in the compiler section. The Polyhedron benchmarks discuss automatic parallelisation. The fortranplus entry covers the diagnostic capability of the Cray, gfortran, Intel, Nag, Oracle and Nvidia compilers. Updated one entry and removed three others from the software tools section. Added ’Fortran Discourse’ to the e-lists section. We have also made changes to the Latex style sheet. • September 2020. Added a computer arithmetic and IEEE formats section. • June 2020. Updated the compiler entry with details of standard conformance.
    [Show full text]
  • R Course for the Nsos in the Arab Countries Part I: Introduction
    R Course for the NSOs in the Arab countries Part I: Introduction Valentin Todorov1 1United Nations Industrial Development Organization, Vienna 18-20 May 2015 Todorov (UNIDO) R Course for the NSOs in the Arab countriesPart I: Introduction18-20 May 2015 1 / 1 Outline Todorov (UNIDO) R Course for the NSOs in the Arab countriesPart I: Introduction18-20 May 2015 2 / 1 About R Outline Todorov (UNIDO) R Course for the NSOs in the Arab countriesPart I: Introduction18-20 May 2015 3 / 1 About R What is R • R is a language and environment for statistical computing and graphics • R is based on the S language originally developed by John Chambers and colleagues at AT&T Bell Labs in the late 1970s and early 1980s • R (sometimes called "GNU S\ ) is free open source software licensed under the GNU general public license (GPL 2) • R was created by Robert Gentleman and Ross Ihaka at the University of Auckland as a test bed for trying out some ideas in statistical computing • R is formally known as The R Project for Statistical Computing: http://www.r-project.org Todorov (UNIDO) R Course for the NSOs in the Arab countriesPart I: Introduction18-20 May 2015 4 / 1 About R The R project • The R Project is an international collaboration of researchers in statistical computing. • There are roughly 20 members of the "R Core Team\ who maintain and enhance R. • Releases of the R environment are made through the CRAN (comprehensive R archive network) twice per year. • The software is released under a "free software\ license, which makes it possible for anyone to download and use it.
    [Show full text]
  • C++ Data Types
    Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 2 (Part II) Introduction to C++ The char Data Type (Sample Program) Character and String Constants The char Data Type Program 2-12 assigns character constants to the variable letter. Anytime a program works with a character, it internally works with the code used to represent that character, so this program is still assigning the values 65 and 66 to letter. Character constants can only hold a single character. To store a series of characters in a constant we need a string constant. In the following example, 'H' is a character constant and "Hello" is a string constant. Notice that a character constant is enclosed in single quotation marks whereas a string constant is enclosed in double quotation marks. cout << ‘H’ << endl; cout << “Hello” << endl; The char Data Type Strings, which allow a series of characters to be stored in consecutive memory locations, can be virtually any length. This means that there must be some way for the program to know how long the string is. In C++ this is done by appending an extra byte to the end of string constants. In this last byte, the number 0 is stored. It is called the null terminator or null character and marks the end of the string. Don’t confuse the null terminator with the character '0'. If you look at Appendix A you will see that the character '0' has ASCII code 48, whereas the null terminator has ASCII code 0.
    [Show full text]
  • Travels in TEX Land: Choosing a TEX Environment for Windows
    The PracTEX Journal TPJ 2005 No 02, 2005-04-15 Rev. 2005-04-17 Travels in TEX Land: Choosing a TEX Environment for Windows David Walden The author of this column wanders through world of TEX, as a non-expert, reporting what he observes and learns, which hopefully will be interesting to other non-expert users of TEX. 1 Introduction This column recounts my experiences looking at and thinking about different ways TEX is set up for users to go through the document-composition to type- setting cycle (input and edit, compile, and view or print). First, I’ll describe my own experience randomly trying various TEX environments. I suspect that some other users have had a similar introduction to TEX; and perhaps other users have just used the environment that was available at their workplace or school. Then I’ll consider some categories for thinking about options in TEX setups. Last, I’ll suggest some follow-on steps. Since I use Microsoft Windows as my computer operating system, this note focuses on environments that are available for Windows.1 2 My random path to choosing a TEX environment 2 I started using TEX in the late 1990s. 1But see my offer in Section 4. 2 While I started using TEX, I switched from TEX to using LATEX as soon as I discovered LATEX existed. Since both TEX and LATEX are operated in the same way, I’ll mostly refer to TEX in this note, since that is the more basic system. c 2005 David C. Walden I don’t quite remember my first setup for trying TEX.
    [Show full text]
  • How to Write a Paper and Format It Using LATEX
    How To Write a Paper and Format it Using LATEX Jennifer E. Hoffman1, 2, ∗ 1Department of Physics, Harvard University, Cambridge, Massachusetts 02138, USA 2School of Engineering & Applied Sciences, Harvard University, Cambridge, Massachusetts 02138, USA (Dated: July 30, 2020) The goal of this document is to demonstrate how to write a paper. We walk through the process of outlining, writing, formatting in LATEX, making figures, referencing, and checking style and content. Source files are available at: http://hoffman.physics.harvard.edu/example-paper/. I. GETTING STARTED 8. Rewrite your abstract, taking into account what you have learned from the process of writing the paper. As You should start writing your paper while you are you fine-tune your abstract, you may find it helpful to working on your experiment. Prof. George Whitesides refer to Nature's instructions for writing an abstract says: \A paper is not just an archival device for stor- [2] and for clear communication more generally [3]. ing a completed research program; it is also a structure for planning your research in progress. If you clearly As you contemplate the paper you have just writ- understand the purpose and form of a paper, it can be ten, put yourself in the shoes of the reviewers (includ- immensely useful to you in organizing and conducting ing your collaborators). You already work many, many your research. A good outline for the paper is also a hours/week, and you don't really want to spend more good plan for the research program. You should write time reading this paper. So you're going to be very happy and rewrite these plans/outlines throughout the course if the figures are pretty, the text flows logically, the ref- of the research.
    [Show full text]
  • Miktex Manual Revision 2.0 (Miktex 2.0) December 2000
    MiKTEX Manual Revision 2.0 (MiKTEX 2.0) December 2000 Christian Schenk <[email protected]> Copyright c 2000 Christian Schenk Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the con- ditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another lan- guage, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. Chapter 1: What is MiKTEX? 1 1 What is MiKTEX? 1.1 MiKTEX Features MiKTEX is a TEX distribution for Windows (95/98/NT/2000). Its main features include: • Native Windows implementation with support for long file names. • On-the-fly generation of missing fonts. • TDS (TEX directory structure) compliant. • Open Source. • Advanced TEX compiler features: -TEX can insert source file information (aka source specials) into the DVI file. This feature improves Editor/Previewer interaction. -TEX is able to read compressed (gzipped) input files. - The input encoding can be changed via TCX tables. • Previewer features: - Supports graphics (PostScript, BMP, WMF, TPIC, . .) - Supports colored text (through color specials) - Supports PostScript fonts - Supports TrueType fonts - Understands HyperTEX(html:) specials - Understands source (src:) specials - Customizable magnifying glasses • MiKTEX is network friendly: - integrates into a heterogeneous TEX environment - supports UNC file names - supports multiple TEXMF directory trees - uses a file name database for efficient file access - Setup Wizard can be run unattended The MiKTEX distribution consists of the following components: • TEX: The traditional TEX compiler.
    [Show full text]
  • Floating Point Numbers
    Floating Point Numbers CS031 September 12, 2011 Motivation We’ve seen how unsigned and signed integers are represented by a computer. We’d like to represent decimal numbers like 3.7510 as well. By learning how these numbers are represented in hardware, we can understand and avoid pitfalls of using them in our code. Fixed-Point Binary Representation Fractional numbers are represented in binary much like integers are, but negative exponents and a decimal point are used. 3.7510 = 2+1+0.5+0.25 1 0 -1 -2 = 2 +2 +2 +2 = 11.112 Not all numbers have a finite representation: 0.110 = 0.0625+0.03125+0.0078125+… -4 -5 -8 -9 = 2 +2 +2 +2 +… = 0.00011001100110011… 2 Computer Representation Goals Fixed-point representation assumes no space limitations, so it’s infeasible here. Assume we have 32 bits per number. We want to represent as many decimal numbers as we can, don’t want to sacrifice range. Adding two numbers should be as similar to adding signed integers as possible. Comparing two numbers should be straightforward and intuitive in this representation. The Challenges How many distinct numbers can we represent with 32 bits? Answer: 232 We must decide which numbers to represent. Suppose we want to represent both 3.7510 = 11.112 and 7.510 = 111.12. How will the computer distinguish between them in our representation? Excursus – Scientific Notation 913.8 = 91.38 x 101 = 9.138 x 102 = 0.9138 x 103 We call the final 3 representations scientific notation. It’s standard to use the format 9.138 x 102 (exactly one non-zero digit before the decimal point) for a unique representation.
    [Show full text]
  • Floating Point Numbers and Arithmetic
    Overview Floating Point Numbers & • Floating Point Numbers Arithmetic • Motivation: Decimal Scientific Notation – Binary Scientific Notation • Floating Point Representation inside computer (binary) – Greater range, precision • Decimal to Floating Point conversion, and vice versa • Big Idea: Type is not associated with data • MIPS floating point instructions, registers CS 160 Ward 1 CS 160 Ward 2 Review of Numbers Other Numbers •What about other numbers? • Computers are made to deal with –Very large numbers? (seconds/century) numbers 9 3,155,760,00010 (3.1557610 x 10 ) • What can we represent in N bits? –Very small numbers? (atomic diameter) -8 – Unsigned integers: 0.0000000110 (1.010 x 10 ) 0to2N -1 –Rationals (repeating pattern) 2/3 (0.666666666. .) – Signed Integers (Two’s Complement) (N-1) (N-1) –Irrationals -2 to 2 -1 21/2 (1.414213562373. .) –Transcendentals e (2.718...), π (3.141...) •All represented in scientific notation CS 160 Ward 3 CS 160 Ward 4 Scientific Notation Review Scientific Notation for Binary Numbers mantissa exponent Mantissa exponent 23 -1 6.02 x 10 1.0two x 2 decimal point radix (base) “binary point” radix (base) •Computer arithmetic that supports it called •Normalized form: no leadings 0s floating point, because it represents (exactly one digit to left of decimal point) numbers where binary point is not fixed, as it is for integers •Alternatives to representing 1/1,000,000,000 –Declare such variable in C as float –Normalized: 1.0 x 10-9 –Not normalized: 0.1 x 10-8, 10.0 x 10-10 CS 160 Ward 5 CS 160 Ward 6 Floating
    [Show full text]