学习要点

  1. 人类的大脑并不太擅长计算,而刚开始发明计算机的目的就是为了计算。以前数学家和物理学家要花几个小时才能计算出来的数据,现在计算机不到几分之一秒就可以就算出来。
  2. 了解数学表达式加(+)、减(-)、乘(*)、除(/)、取余(%)。
  3. 了解变量赋值、使用

代码示例

#include<iostream>

/**
 * 本例子(area-fixed.cc)通过计算长方形、正方形、圆的周长和面积计算,学习数学表达式。
 *
 * 知识点:
 *     1. [数学表达式](https://cs.jingxuanqu.com/csp/programming/mathematical-expressions.html)
 */
using namespace std;
int main(){
    //长方形的长为8,宽为4
    int c_rectangle = (8 + 4) * 2; //【知识点】加法、乘法
    int s_rectangle = 8 * 4;
    cout << "长方形(长为8,宽为4)的周长是: " << c_rectangle << " 面积是: " << s_rectangle << endl;
    cout << endl;
    
    //和长方形周长相等的正方形的面积计算
    float side = c_rectangle/4;  //和长方形周长相同
    float c_square = side * 4;
    float s_square = side * side;
    cout << "正方形(边长为6)的周长是: " << c_square << " 面积是: " << s_square << endl;
    float s_more = s_square - s_rectangle;  //【知识点】减法
    cout << "正方形的面积比长方形多: "  << s_more << endl; 
    cout << endl;

    //和长方形周长相等的圆的面积计算
    float r = c_rectangle/(2*3.14);  //【知识点】除法
    float c_circle = 2 * 3.14 * r;
    float s_circle = 3.14 * (r * r); 
    cout << "圆(半径为" << r <<")的周长是: " << c_circle << " 面积是: " << s_circle << endl;
    cout << "圆的面积比长方形多: "  << s_circle - s_rectangle << endl;
    cout << endl;

    //一段10000米长的钢材,截成168米的小段用于铁索桥,剩余多少米?
    int total = 10000;
    int part = 168;
    int remain = total % part;  //【知识点】取余
    cout << "一段" << total << "米长的钢材,截成" << part << "米的小段用于铁索桥,剩余多少米?" << remain << endl;
    

}

作业

尝试编写一个程序,对于面积相等的长方形(20x8)、正方形、圆,他们的周长差是多少?

Introduction

Computers are incredibly good at math. In fact, that’s why computers were originally invented! Mathematicians and physicists used to spend hours calculating results from their formulas and data. Now, a computer can “compute” results for them in a fraction of a second.

So how do we actually get the computer to do math for us?

Arithmetic operators

Programming languages come with arithmetic operators, and we can use those to create mathematical expressions.

The Python language provides these operators:

operator operation example result
+ addition 33 + 67 100
- subtraction 1024 - 256 768
* multiplication 12 * 12 144
/ division 144 / 12 12
% remainder 10 % 3 1

Many of those likely look familiar, and are the same operations you use calculators for in math class. However, most new programmers have never seen %, the remainder operator.

The expression 10 % 3 calculates the remainder of 10 divided by 3. The result is 1, since 10 / 3 equals 3 and leaves a remainder of 1.

The remainder operator is often called the “modulo” operator, so we typically read the expression 10 % 3 as “10 mod 3”.

Multiple operators

We can make longer expressions, like this one that calculates the number of minutes in a year:

60 * 24 * 365

We can also combine different operators in the same expression, like this one that converts the temperature of 77°F to Celsius:

(77 - 32) * 5/9

When an expression involves different operators, C++ follows an order of operations for deciding what operations to evaluate first, like multiplying before subtracting. However, it’s often best to use parentheses to make the order obvious and reduce the likelihood of making a mistake.

Storing with variables

We’ll often want to store the results of mathematical expressions in variables, especially if we want to reuse the results of a calculation later. This line of C++ stores the number of milliseconds in 1 hour:

int hour_ms = 1000 * 60 * 60;

Once that line runs, the variable hourMS stores a value of 3600000 and we can reference that variable later in our program. We can also use variables inside mathematical expressions, as long as those variables store numbers.

int two_hours_ms = 2 * hour_ms;

## Pseudocode for mathematical expressions [What's pseudocode?](understanding-pseudocode.html) The majority of programming languages use the same operators for basic arithmetic: +, -, * , /. That's also how we represent them in pseudocode: | Instruction | Explanation | |--------------|------------------------------------------------| | a + b | Evaluates to the result of b added to a | | a - b | Evaluates to the result of b subtracted from a | | a * b | Evaluates to the result of a multiplied by b | | a / b | Evaluates to the result of a divided by b | The remaining operator is the remainder operator, which varies more across languages. Here's how we represent it in our pseudocode: | Instruction | Explanation | |--------------|------------------------------------------------------------------------------------------------| | a MOD b | Evaluates to the remainder when a is divided by b. Assumes that a and b are positive integers. | ## 扩充知识(仅供初步了解) 1. 需要注意的是,这里的除法不支持分数形式。两个数相除,最后会变成一个小数。假如需要保留分数形式做运算,可以适用Fraction这个工具类。示例如下:
1
2
3
4
5
6
from fractions import Fraction

print(11/35)  #会自动变为小数

a = Fraction(11,35) #保留分数形式
print("Fraction: " + str(a))

解决的问题

计算一个圆的面积 S = πr2
输入:r
输出:S
常数:π

知识点

  1. 怎么输入?
  2. 怎么做数学运算?参考数学表达式
  3. 一些数学的常用值的使用(常量)
  4. 小数计算的精度、输出的精度。

代码示例

输入、变量、数学表达式

#include<iostream>

/**
 * 本例子实现面积的计算,公式 S = πr²,π取3.14
 *
 * 知识点:
 *     1. 输入变量的值
 *     2. [数学表达式](https://cs.jingxuanqu.com/csp/programming/mathematical-expressions.html)
 */
using namespace std;
int main(){
    double r; //半径
    cout << "Please enter the radius:";
    //【知识点】输入使用cin (character input)输入数字或者字符串。
    cin >> r; 
    double s = 3.14 * (r * r); //面积
    cout << "Area of a circle with radius " << r << " unit is(π=3.14): " << s << endl;

    //【发掘点】多尝试不同大小的数,打印出来的面积的值是否精确?
}

数学常量

#include<iostream>
#include <cmath>  //一些常用的数学计算工具

using namespace std;
int main(){
    double r; 
    cout << "Please enter the radius:";
    cin >> r; 
    double s = M_PI * (r * r);  //这里用比较精确的pi值
    cout << "Area of a circle with radius " << r << " unit is(π=M_PI): " << s << endl; //输出数值的经度未调整
}

控制结果的输出精度

#include<iostream>
#include<cmath>
#include<iomanip> // std::setprecision

/**
 * 知识点
 *     1. 设置输出值的精度 
 *     2. 浮点的精度问题。float最多精确到7位,double最多精确到15位,在后面的小数的存储章节再重点介绍。
 */
using namespace std;
int main(){
    double r; //圆的半径
    cout << "Please enter the radius:";
    cin >> r; 
    double s = M_PI * (r * r);  
    cout << setprecision(15); //【知识点】设置显示共15位(整数部分+小数部分)
    cout << "M_PI is:" << M_PI <<endl; 

    //【发掘点】小数的精度问题。注意输入值为整数、小数时的差异。先存一个疑问。
    cout << "r is:" << r <<endl; 
    cout << "Area of a circle with radius " << r << " unit is(π=M_PI): " << s << endl;
}

目标

  1. 通过解决一道数学题来讲解数学函数和常量。
  2. 更多的常量,常量初探在前一章介绍。

常用数学函数

开方、指数等函数。

作业

后续递归中用:斐波拉契数列

With just the basic arithmetic operations (+, -, *, /), we can write programs to compute anything that a simple calculator can compute.

What about equaling the power of a scientific calculator, with the ability to calculate sines, exponents, and logs? Programming languages often provide built-in procedures and constants for such advanced mathematical functionality.

Mathematical procedures

Let’s start with the simplest example: calculating the absolute value of a number.

In Python, we can use the built-in procedure fabs():

import math
fabs1 = math.fabs(-5)
print(math.fabs(-5))

We pass a single parameter to the command, the number to process, and the command returns the absolute value of that number. We can either store that result in a variable or we can display it to the screen.

Of course, it’s not very exciting that we can calculate the absolute value of negative 5: we already know that it’s 5. What's exciting is that we can pass in any expression to that procedure, and it will calculate the result.

import math
result = math.fabs( (33 * 1/2) - (40 * 0.75) )

The result is 13.5, and I sure am happy that I asked the computer to calculate that one for me.

The Python language provides many math procedures. Here are some you’re likely to use in your own programs:

Procedure Description
math.floor(num) Returns the largest integer less than or equal to num.
math.ceil(num) Returns the smallest integer greater than or equal to num.
math.sin(num) Returns the sine of num, an angle specified in radians.
math.cos(num) Returns the cosine of num, an angle specified in radians.
math.tan(num) Returns the tangent of num, an angle specified in radians.
math.pow(x, y) Return x raised to the power y.

✏️ Check them all out in the program below and try plugging in different numbers. You can also look up other available procedures from the Math documentation(Opens in a new window) and try them out here.

Math constants

The field of math includes a number of special numbers. The most famous is probably π, since it pops up in all things circular. If you’ve memorized the first dozen digits of π, then you can go ahead and type that in your programs… For the rest of us mere mortals, we can rely on programming languages to memorize those digits for us.

In JavaScript, we can get an approximate value of π by referencing math.pi, a variable that’s already defined in every JS program.

For example, this expression calculates the circumference of a circle with radius 12:

circumference = 2 * math.pi * 12;

The math.pi variable is a constant, which means it can’t be re-assigned. We can trust our math more when we know that π will always be π.

You can learn about Python’s other math constants in the math reference. Most languages will provide similar constants, so if you’re in another language, you can search online for “Pi in [programming language]”.

✏️The program below uses math.pi and math.pow() to help us answer the age old question: what pizza size should you buy? Change it to reflect your local pizza joint’s prices and see how the results change.

Math in pseudocode

In pseudocode, you will likely see a built-in mathematical procedure described like this:

Pseudocode Description
ABS(num) Returns the absolute value of num

That pseudocode can be used like this:

abs1 ← ABS(-5)
DISPLAY( ABS(-5) )

In pseudocode, constants are written in all caps, like the constant PI.

An expression to calculate circumference could be written like this:

circumference ← 2 * PI * radius

1. 解决的问题

  1. 看看2的10次方,20次方,30次方分别由多大?存储单位上,这三个数分别对应KB、MB、GB。实际上大致对应一篇文章、一张照片、一部电影的文件大小。

2. 知识点

2.1 计算一个数的n次方

print(pow(2, 8))  #2的8次方

import math
print(math.pow(2, 8))  #注意观察和写法上和结果,和上面的有什么区别?

import numpy as np
print(np.power(2,8))   # 可以对单个数字进行n次方运算
a = [2,3,4,5,6,7,8,9]
print(np.power(a,8))   # 也可以对一组数进行n次方运算

知识点滴 编程语言中,有很多现成的过程可以用,例如上面的n次方过程pow。为了方便大家查找使用,这些过程一般用模块的方式组织起来,例如上面的math模块,里面就包含很多的过程,如取绝对值、平方、开方等等。当需要使用某个模块时,用import xx的方式声明一下。

2.2 计算圆的面积

import math.pi

r = 25 #半径是25
S = math.pi * r * r #Python中,所有的变量一般用小写,这里为了含义清晰,暂用大写
print(S)

知识点滴 这里的math.pi是一个常量,不会变,也不能修改。

3. 学习总结

  1. 了解基本的数学用途的过程(procedure)和数学常量