Skip to content

Commit

Permalink
Merge pull request #65 from mei1127/add_constant
Browse files Browse the repository at this point in the history
Completed constant
  • Loading branch information
huningxin authored Jan 11, 2024
2 parents 32c2d3c + 3925196 commit 86338a5
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

import {cast} from './cast.js';
import {Tensor, sizeOfShape} from '../src/lib/tensor.js';
/**
* Create a constant array of specified data type and shape,
* which contains data incrementing by step.
* @param {Number} start
* @param {Number} step
* @param {Array} outputShape
* @param {string} type
* @return {Tensor}
*/
export function constant(start, step, outputShape, type = 'float32') {
const outputElementCount = sizeOfShape(outputShape);
const data = [];
for (let i = 0; i < outputElementCount; i++) {
data.push(start + i * step);
}
const tensor = new Tensor(outputShape, data);
return cast(tensor, type);
}
60 changes: 60 additions & 0 deletions test/constant_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict';

import {constant} from '../src/constant.js';
import * as utils from './utils.js';


describe('test constant', function() {
function testConstant(start, step, outputShape, type, expected) {
const outputTensor = constant(start, step, outputShape, type);
utils.checkShape(outputTensor, expected.shape);
utils.checkValue(outputTensor, expected.data);
}

it('constant step > 0', function() {
const expected ={
shape: [3, 3],
data: [
0, 1, 2,
3, 4, 5,
6, 7, 8,
],
};
testConstant(
0, 1, [3, 3], 'float32', expected);
});

it('constant step < 0', function() {
const expected ={
shape: [3, 3],
data: [
9, 8, 7,
6, 5, 4,
3, 2, 1,
],
};
testConstant(
9, -1, [3, 3], 'float32', expected);
});

it('constant step = 0', function() {
const expected ={
shape: [3, 3],
data: [
1, 1, 1,
1, 1, 1,
1, 1, 1,
],
};
testConstant(
1, 0, [3, 3], 'float64', expected);
});

it('constant scalar', function() {
const expected ={
shape: [],
data: [42],
};
testConstant(42, 0, [], 'float64', expected);
});
});

0 comments on commit 86338a5

Please sign in to comment.