
上QQ阅读APP看书,第一时间看更新
2.2.3 Lambda表达式
练习18:用Lambda表达式证明三角恒等式
在这个练习中,我们将使用Lambda表达式来证明著名的三角恒等式(见图2-3)。

图2-3 三角恒等式
1.导入math包:

2.定义两个函数my_sine和my_cosine。声明这两个函数的原因是,math包中的原始sin和cos函数将弧度作为输入,但我们更熟悉角度。所以,我们使用Lambda表达式定义一个无名称的单行函数,该函数自动将输入的角度转换为弧度,然后对其应用sin或cos函数并返回值:

3.根据我们的目的定义sine和cosine:

输出如下:

需要注意的是,我们已经将my_sine和my_cosine的返回值赋给了两个变量,然后将它们直接用作函数。这是一种比直接使用它们更简洁的方法。另外,我们没有在Lambda函数内显式写入return语句。