【Day 27】NumPy (4):np.sqrt(), np.square()

前言

今天要来介绍一下用於数学运算的函式,sqrt 开根号,以及 square 平方

NumPy

np.sqrt()

把输入 array 的每个元素都取平方根并回传,完整的语法如下。

np.sqrt(arr, out = None)

  • arr :代表输入的 array。
  • out :如果有 out,会将结果储存在 out 内,此 out 要和 arr 的形状一样。
import numpy as np

array1 = np.array([1, 4, 9, 16])    # 建立一个 array
out_array = np.zeros(4)             # 建立一个空的 array,大小和 array1 一样大
print(out_array)                    # 检查建立的 array
# [0. 0. 0. 0.]

x = np.sqrt(array1, out_array)    # 把 array 内的元素都取平方根并放入 x,以及放入 out_array

print(x)
# 输出
# [1. 2. 3. 4.]

print(out_array)
# 输出
# [1. 2. 3. 4.]
  • outarr 的形状不一样,就会出现 ValueError

    import numpy as np
    
    array1 = np.array([1, 4, 9, 16])
    out_array = np.zeros((2, 2))
    print(out_array)
    
    
    x = np.sqrt(array1, out_array)
    
    print(x)
    print(out_array)
    

  • 对负数使用 np.sqrt()

    import numpy as np
    
    array1 = np.array([-1, -4, -9, -16])
    
    x = np.sqrt(array1)
    
    print(x)
    

    出现 RuntimeWarning,并回传 nan(非数值)

  • 对复数使用 np.sqrt()

    import numpy as np
    
    array1 = np.array([1j, 4 + 2j , 1j, 3 + 4j])    # 建立一个 array
    
    x = np.sqrt(array1)
    
    print(x)
    # 输出
    # [0.70710678+0.70710678j 2.05817103+0.48586827j 1.41421356+1.41421356j 2.+1.j]
    

    若有两个不同的平方根只会输出一个。

numpy.square()

把输入 array 的每个元素都取平方并回传,完整的语法如下。

np.square(arr, out = None)

  • arr :代表输入的 array。
  • out :如果有 out,会将结果储存在 out 内,此 out 要和 arr 的形状一样。
import numpy as np

array1 = np.array([1, 4, 9, 16])    # 建立一个 array
out_array = np.zeros(4)             # 建立一个空的 array,大小和 array1 一样大
print(out_array)                    # 检查建立的 array
# 输出
# [0. 0. 0. 0.]

x = np.square(array1, out_array)    # 把 array 内的元素都取平方并放入 x,以及放入 out_array

print(x)
# 输出
# [  1.  16.  81. 256.]

print(out_array)

# 输出
# [  1.  16.  81. 256.]
  • outarr 的形状不一样,就会出现 ValueError:同上面 sqrt

  • 对负数使用 np.square()

    import numpy as np
    
    array1 = np.array([-1, -4, -9, -16])
    
    x = np.square(array1)
    
    print(x)
    # 输出
    # [  1  16  81 256]
    
  • 对复数使用 np.square()

    import numpy as np
    
    array1 = np.array([1 + 5j, 3 + 6j, -9j, 1j])
    
    x = np.square(array1)
    
    print(x)
    # 输出
    # [-24.+10.j -27.+36.j -81. +0.j  -1. +0.j]
    

待续...


<<:  【Day 28】 服务器监控 on AWS

>>:  Day28 JQuery应用

[Day 15] 在Arduino IDE中用Arm CMSIS 牛刀小试一下

在[Day 14] tinyML开发框架(二):Arm CMSIS 简介已初步帮大家介绍了Arm C...

Day 18:数据蒐集、资料视觉化、数据分析

前言 在公司内部总是有大大小小的提案,每个提案都有拥护的人,但是大家各说各话,没有办法公平的做出决定...

铁人赛 Day6 -- PHP SQL基本语法(一)资料库连线 & require_once 引入档案

前言 昨天把资料库建立好之後,我们就要来试着连线我们的资料库 档案名称 : db.php (不罗嗦,...

Day-10 近水楼台先得月

近水楼台先得月 tags: IT铁人 区域性原则 有在组装电脑的人就会知道,电脑的储存装置包括记忆体...

D28 第十六周 (回忆篇)

终於完结第十一周作业 最後集中在两天的时间把部落格作业写出来,前面花时间跟留言板搏斗的经验果然有派上...