JS宏案例:在wps编辑器中玩numpy

ops/2025/3/4 19:01:52/

NumPy 是 Python 中用于科学计算的一个基础库,它提供了大量的数学函数工具,尤其是用于高效处理大型多维数组和矩阵。NumPy 是 Python 数据分析、机器学习、科学计算等领域中不可或缺的一部分。

然,在wps的js宏编辑器中,并没有这样一个模块或是全局对象,但是,问题不大,我们可以手搓一个。不过,要使用JS完全模拟python中的numpy是比较困难的,工作量也非常的大,我们可以适当简化一下,如只对常用方法和属性进行模拟。

一、自定义错误

javascript">class DimensionError extends Error {constructor(message) {super(message);this.name = "维度错误";}
}class ValueError extends Error {constructor(message) {super(message);this.name = "值错误";}
}

上述代码中,定义了一个维度错误和值错误,是py中numpy模块中常见的两种错误。

二、构造Numpy全局对象

1、示例代码:

javascript">class Numpy {constructor(array) {if (array !== undefined && !Array.isArray(array)) {throw new TypeError("the parm array must be array.");} this.#_array = array;}// 获取数组维度get ndim() {let n = 0;let array = this.#_array;while (Array.isArray(array)) {n++;array = array[0];}return n;}// 返回数组的维度,是一个整数数组,表示每个维度中数组的大小。对于具有 n 行和 m 列的矩阵,shape 将是 [n, m]。get shape() {let result = [];let n = this.ndim;let array = this.#_array; while (n > 0) {result.push(array.length);array = array[0];n--;}return result;}// 返回数组中所有元素的个数get size() {let arr = this.shape;let product = 1;for (let i = 0; i < arr.length; i++) {product *= arr[i];}return product;}// 转置get T() {return this.#_transpose(this.#_array);}get random() {// random对象let self = this;return {rand: function(shape) {// 生成shape形状的随机数组,数值用随机数填充if (shape === undefined || shape === null) return Math.random();if (!Array.isArray(shape)) throw new TypeError("param shape must be array.");if (!shape.every(i => Number.isInteger(i)))  throw new TypeError("shape must be array of integer.");return self.full(shape, () => Math.random()); },randn: function(shape) {// 随机正态分布if (typeof shape === "number") shape = [shape]; // 如果 shape 是数字,转换为数组if (!Array.isArray(shape)) throw new TypeError("shape must be a number or array");const totalElements = shape.reduce((acc, val) => acc * val, 1); // 计算总元素个数const result = Array.from({ length: totalElements }, () => self.#_randn()); // 生成随机数// 将一维数组转换为多维数组function reshape(arr, shape) {if (shape.length === 1) return arr;const [currentDim, ...remainingDims] = shape;const result = [];const chunkSize = arr.length / currentDim;for (let i = 0; i < currentDim; i++) {result.push(reshape(arr.slice(i * chunkSize, (i + 1) * chunkSize), remainingDims));}return result;}return new Numpy(reshape(result, shape));},randint: function(low, high = null, size = null) {if (high === null) {high = low;low = 0;}if (low >= high) throw new ValueError("low must be less than high");// 单个随机整数function getRandomInt(low, high) {return Math.floor(Math.random() * (high - low)) + low;}// 如果 size 未提供,返回单个随机数if (size === null) return getRandomInt(low, high);// 如果 size 是数字,转换为数组if (typeof size === "number") size = [size];if (!Array.isArray(size)) throw new TypeError("size must be a number or array");const totalElements = size.reduce((acc, val) => acc * val, 1);const result = Array.from({ length: totalElements }, () => getRandomInt(low, high));function reshape(arr, shape) {if (shape.length === 1) return arr;const [currentDim, ...remainingDims] = shape;const result = [];const chunkSize = arr.length / currentDim;for (let i = 0; i < currentDim; i++) {result.push(reshape(arr.slice(i * chunkSize, (i + 1) * chunkSize), remainingDims));}return result;}return new Numpy(reshape(result, size));},choice: function(a, size = null, replace = true, p = null) {if (typeof a === "number") {a = Array.from({ length: a }, (_, i) => i); // 如果 a 是数字,生成 range(a)}if (!Array.isArray(a)) throw new TypeError("a must be a number or array");if (p !== null) {if (!Array.isArray(p)) throw new TypeError("p must be an array");if (p.length !== a.length) throw new ValueError("a and p must have the same length");if (p.some(prob => prob < 0)) throw new ValueError("probabilities must be non-negative");const totalProb = p.reduce((acc, val) => acc + val, 0);if (Math.abs(totalProb - 1) > 1e-6) throw new ValueError("probabilities must sum to 1");}// 如果 size 未提供,返回单个随机元素if (size === null) {if (p === null) {return a[Math.floor(Math.random() * a.length)];} else {const rand = Math.random();let cumulativeProb = 0;for (let i = 0; i < a.length; i++) {cumulativeProb += p[i];if (rand < cumulativeProb) return a[i];}}}// 如果 size 是数字,转换为数组if (typeof size === "number") size = [size];if (!Array.isArray(size)) throw new TypeError("size must be a number or array");const totalElements = size.reduce((acc, val) => acc * val, 1);const result = [];for (let i = 0; i < totalElements; i++) {if (p === null) {const randomIndex = Math.floor(Math.random() * a.length);result.push(a[randomIndex]);if (!replace) a.splice(randomIndex, 1); // 如果不允许重复,移除已选元素} else {const rand = Math.random();let cumulativeProb 

http://www.ppmy.cn/ops/163098.html

相关文章

05. Springboot admin集成Actuator(一)

目录 1、前言 2、Actuator监控端点 2.1、健康检查 2.2、信息端点 2.3、环境信息 2.4、度量指标 2.5、日志文件查看 2.6、追踪信息 2.7、Beans信息 2.8、Mappings信息 3、快速使用 2.1、添加依赖 2.2、添加配置文件 2.3、启动程序 4、自定义端点Endpoint 5、自定…

【星云 Orbit • STM32F4】04.一触即发:GPIO 外部中断

【星云 Orbit- • STM32F4】04. 一触即发&#xff1a;外部中断控制 摘要 本文详细介绍了如何使用STM32F407微控制器的HAL库实现外部中断功能。通过配置GPIO引脚作为外部中断源&#xff0c;并在中断回调函数中处理按键事件&#xff0c;实现了按键控制LED状态翻转的功能。本文旨…

C# Equals 和 ReferenceEquals 使用详解

总目录 前言 在C#中&#xff0c;Equals 方法和 ReferenceEquals 方法用于比较对象&#xff0c;但它们的用途和行为有着显著的区别。理解这两者的差异对于编写高效且无误的代码至关重要。 一、Equals 方法 1. 定义 Equals 是 System.Object 类中的一个虚方法&#xff0c;用于…

【练习】【贪心】力扣452. 用最少数量的箭引爆气球

题目 用最少数量的箭引爆气球 有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points &#xff0c;其中points[i] [xstart, xend] 表示水平直径在 xstart 和 xend之间的气球。你不知道气球的确切 y 坐标。 一支弓箭可以沿着 x 轴从不同点 完全垂直…

基于DeepSeek与Swarm的全场景多智能体客服实战解析(含全套源码)

本文来自九天老师的公开课&#xff0c;由赋范空间运营进行整理编辑&#xff0c;如果你有任何建议欢迎评论告知哦~ DeepSeek v3可以说是智能体开发的首选模型没有之一&#xff01; 模型综合性能和GPT4o相当&#xff0c;价格只需要GPT4o的1/20&#xff0c;并且支持Function cal…

Python for Data Analysis第二版【中文版】-第六章

访问数据是使用本书所介绍的这些工具的第一步。我会着重介绍pandas的数据输入与输出&#xff0c;虽然别的库中也有不少以此为目的的工具。 输入输出通常可以划分为几个大类&#xff1a;读取文本文件和其他更高效的磁盘存储格式&#xff0c;加载数据库中的数据&#xff0c;利用…

计算机网络-实验四子网划分

三、实验内容及步骤 1.要求 【题目】某单位申请了⼀个 C 类⽹络&#xff0c;单位内部有3个部门&#xff0c;各部门约50台主机&#xff0c;需要划分为3个⼦⽹&#xff0c;各部门接⼊到汇聚交换机&#xff0c;在汇聚层进⾏路由连通。假定申请到的C类网络为200.200.200.0。 2.实…

配置Spring Boot API接口超时时间(五种)

1、简介 在开发API接口时&#xff0c;配置API接口的超时时间是一项非常重要的任务。超时时间的设置对于确保系统的稳定性和响应性至关重要。当客户端发送请求到服务器时&#xff0c;如果服务器由于某些原因&#xff08;如数据库查询缓慢、外部服务调用失败等&#xff09;无法及…