Compare commits

...

12 Commits

Author SHA1 Message Date
bccf00766f version bump 1.1.3 2024-04-23 16:12:51 -04:00
d07f3c99c7 update dev deps and tooling 2020-05-13 17:16:25 -04:00
e993b565c8 License text 2019-10-10 18:33:06 -04:00
4d295d7900 version bump 1.1.2: node module cleanup [ci skip] 2018-02-20 15:57:28 -05:00
9ef2c47f04 version bump 1.1.1: infrastructure 2018-01-19 00:03:42 -05:00
4cb7279d62 version bump 1.1.0: pin dependencies 2017-07-27 23:19:00 -04:00
395ea31e95 version bump 1.0.6: module cleanup 2017-04-29 13:32:07 -04:00
5d66247109 browser test 2017-03-29 03:08:09 -04:00
93ff7f307a version bump 1.0.5: adjusting tolerance 2016-09-23 01:43:23 -04:00
63e6cf4bb3 version bump 1.0.4: adjusting tolerance 2016-01-16 01:37:17 -05:00
ce5054af79 typo in setup.py [ci skip] 2015-05-05 00:16:39 -07:00
9a9ed4d1fa version bump 1.0.2: cleanup
- cont: more direct reverse iteration
- README cleanup
- python linting and tests
2015-05-04 23:19:23 -07:00
38 changed files with 8752 additions and 245 deletions

24
.eslintrc Normal file

@ -0,0 +1,24 @@
{
"env": { "shared-node-browser":true },
"globals": {},
"parserOptions": {
"ecmaVersion": 3
},
"plugins": [ "html", "json" ],
"extends": "eslint:recommended",
"rules": {
"comma-style": [ 2, "last" ],
"comma-dangle": [ 2, "never" ],
"curly": 0,
"no-bitwise": 0,
"no-console": 0,
"no-control-regex": 0,
"no-empty": 0,
"no-trailing-spaces": 2,
"no-use-before-define": [ 1, {
"functions":false, "classes":true, "variables":false
}],
"no-useless-escape": 0,
"semi": [ 2, "always" ]
}
}

@ -1,6 +1,8 @@
[ignore]
.*/node_modules/.*
.*/dist/.*
.*/ctest/mocha.js
.*/ctest/sauce.*
.*/test.js
.*/frac.js

9
.gitignore vendored Normal file

@ -0,0 +1,9 @@
.gitignore
node_modules/
coverage.html
*.sheetjs
*.pyc
build/
MANIFEST
*.gz
*.tgz

@ -1,8 +1,15 @@
frac.flow.js
frac.md
test_files/*.tsv
ctest/
test.js
Makefile
.gitignore
.npmignore
node_modules/
coverage.html
.travis.yml
.eslintrc
.jshintrc
.jscs.json
.flowconfig
@ -13,3 +20,6 @@ build/
MANIFEST
*.gz
*.tgz
*.py
*.html
.spelling

8
.spelling Normal file

@ -0,0 +1,8 @@
# frac.js (C) 2012-present SheetJS -- http://sheetjs.com
SheetJS
frac
Aberth
CommonJS
npm
prepend

@ -1,10 +1,15 @@
language: node_js
node_js:
- "iojs"
- "7"
- "6"
- "5"
- "4"
- "0.12"
- "0.10"
- "0.8"
before_install:
- "npm install -g mocha"
- "npm install -g npm@4.3.0"
- "npm install -g mocha@2.x voc"
- "npm install blanket"
- "npm install coveralls mocha-lcov-reporter"
after_success:

190
LICENSE

@ -1,4 +1,192 @@
Copyright (C) 2012-2015 SheetJS
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2012-present SheetJS LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

101
Makefile

@ -2,59 +2,94 @@ LIB=frac
REQS=
ADDONS=
AUXTARGETS=
CMDS=
HTMLLINT=index.html
ULIB=$(shell echo $(LIB) | tr a-z A-Z)
DEPS=$(LIB).md
TARGET=$(LIB).js
FLOWTARGET=$(LIB).flow.js
UGLIFYOPTS=--support-ie8
CLOSURE=/usr/local/lib/node_modules/google-closure-compiler/compiler.jar
## Main Targets
.PHONY: all
all: $(TARGET) $(AUXTARGETS)
all: $(TARGET) $(AUXTARGETS) ## Build library and auxiliary scripts
$(TARGET) $(AUXTARGETS): %.js : %.flow.js
node -e 'process.stdout.write(require("fs").readFileSync("$<","utf8").replace(/^\s*\/\*:[^*]*\*\/\s*(\n)?/gm,"").replace(/\/\*:[^*]*\*\//gm,""))' > $@
node -e 'process.stdout.write(require("fs").readFileSync("$<","utf8").replace(/^[ \t]*\/\*[:#][^*]*\*\/\s*(\n)?/gm,"").replace(/\/\*[:#][^*]*\*\//gm,""))' > $@
$(LIB).flow.js: $(DEPS)
voc $^
$(FLOWTARGET): $(DEPS)
voc $^ || npx voc $^
.PHONY: clean
clean:
rm -f $(TARGET)
clean: ## Remove targets and build artifacts
rm -f $(TARGET) $(FLOWTARGET)
## JavaScript
.PHONY: test mocha
test mocha: test.js
test mocha: test.js $(TARGET) ## Run JS test suite
mocha -R spec -t 20000
.PHONY: ctest
ctest: ## Build browser test (into ctest/ subdirectory)
browserify -t brfs test.js > ctest/test.js
cp -f $(TARGET) ctest/
.PHONY: ctestserv
ctestserv: ## Start a test server on port 8000
@cd ctest && python -mSimpleHTTPServer || python3 -mhttp.server || npx -y http-server -p 8000 .
.PHONY: fullint
fullint: lint old-lint tslint flow mdlint ## Run all checks
.PHONY: lint
lint: $(TARGET) $(AUXTARGETS)
jshint --show-non-errors $(TARGET) $(AUXTARGETS)
jshint --show-non-errors package.json
jscs $(TARGET) $(AUXTARGETS)
lint: $(TARGET) $(AUXTARGETS) ## Run eslint checks
@eslint --ext .js,.njs,.json,.html,.htm $(TARGET) $(AUXTARGETS) $(CMDS) $(HTMLLINT) package.json
if [ -e $(CLOSURE) ]; then java -jar $(CLOSURE) $(REQS) $(FLOWTARGET) --jscomp_warning=reportUnknownTypes >/dev/null; fi
.PHONY: old-lint
old-lint: $(TARGET) $(AUXTARGETS) ## Run jshint and jscs checks
@jshint --show-non-errors $(TARGET) $(AUXTARGETS)
@jshint --show-non-errors $(CMDS)
@jshint --show-non-errors package.json
@jshint --show-non-errors --extract=always $(HTMLLINT)
@jscs $(TARGET) $(AUXTARGETS)
if [ -e $(CLOSURE) ]; then java -jar $(CLOSURE) $(REQS) $(FLOWTARGET) --jscomp_warning=reportUnknownTypes >/dev/null; fi
.PHONY: tslint
tslint: $(TARGET) ## Run typescript checks
#@npm install dtslint typescript
#@npm run-script dtslint
dtslint types
.PHONY: flow
flow: lint
flow check --all --show-all-errors
flow: lint ## Run flow checker
@flow check --all --show-all-errors
.PHONY: cov cov-spin
cov: misc/coverage.html
cov-spin:
make cov & bash misc/spin.sh $$!
.PHONY: cov
cov: misc/coverage.html ## Run coverage test
misc/coverage.html: $(TARGET) test.js
mocha --require blanket -R html-cov -t 20000 > $@
.PHONY: coveralls coveralls-spin
coveralls:
mocha --require blanket --reporter mocha-lcov-reporter -t 20000 | ./node_modules/coveralls/bin/coveralls.js
.PHONY: coveralls
coveralls: ## Coverage Test + Send to coveralls.io
mocha --require blanket --reporter mocha-lcov-reporter -t 20000 | node ./node_modules/coveralls/bin/coveralls.js
coveralls-spin:
make coveralls & bash misc/spin.sh $$!
MDLINT=README.md frac.md
.PHONY: mdlint
mdlint: $(MDLINT) ## Check markdown documents
alex $^
mdspell -a -n -x -r --en-us $^
.PHONY: dist
dist: dist-deps $(TARGET)
dist: dist-deps $(TARGET) ## Prepare JS files for distribution
cp $(TARGET) dist/
cp LICENSE dist/
uglifyjs $(TARGET) -o dist/$(LIB).min.js --source-map dist/$(LIB).min.map --preamble "$$(head -n 1 frac.js)"
uglifyjs $(UGLIFYOPTS) $(TARGET) -o dist/$(LIB).min.js --source-map dist/$(LIB).min.map --preamble "$$(head -n 1 frac.js)"
misc/strip_sourcemap.sh dist/$(LIB).min.js
.PHONY: aux
@ -65,10 +100,24 @@ dist-deps:
## Python
.PHONY: pylint
pylint: frac.py
pylint: frac.py $(wildcard test_*.py) ## Run pep8 check
pep8 $^
.PHONY: pypi
pypi: frac.py
pydist: frac.py ## Upload Python module to PyPI
python setup.py sdist upload
.PHONY: pytest pypytest
pytest: pylint ## Run Python test suite
py.test -v --durations=5
pypytest: pylint ## Run Python test suite in pypy
pypy $$(which py.test) -v --durations=5
.PHONY: help
help:
@grep -hE '(^[a-zA-Z_-][ a-zA-Z_-]*:.*?|^#[#*])' $(MAKEFILE_LIST) | bash misc/help.sh
#* To show a spinner, append "-spin" to any target e.g. cov-spin
%-spin:
@make $* & bash misc/spin.sh $$!

1
README

@ -1 +0,0 @@
README.md

103
README.md

@ -6,24 +6,39 @@ Uses the [Mediant Method](https://en.wikipedia.org/wiki/Mediant_method).
This module also provides an implementation of the continued fraction method as
described by Aberth in "A method for exact computation with rational numbers".
The algorithm is used in <a href="http://sheetjs.com">SheetJS Libraries</a> to
replicate fraction formats.
## Installation
With [npm](https://www.npmjs.org/package/frac):
### JS
$ npm install frac
For NodeJS:
```bash
$ npm i --save https://cdn.sheetjs.com/frac-1.1.3/frac-1.1.3.tgz
```
In the browser:
<script src="frac.js"></script>
```html
<script src="https://cdn.sheetjs.com/frac-1.1.3/package/dist/frac.min.js"></script>
```
The script will manipulate `module.exports` if available (e.g. in a CommonJS
`require` context). This is not always desirable. To prevent the behavior,
define `DO_NOT_EXPORT_FRAC`
The script will manipulate `module.exports` if available . This is not always
desirable. To prevent the behavior, define `DO_NOT_EXPORT_FRAC`
### Python
From [`PyPI`](https://pypi.python.org/pypi/frac):
```bash
$ pip install frac
```
## Usage
The exported `frac` function takes three arguments:
In all cases, the relevant function takes 3 arguments:
- `x` the number we wish to approximate
- `D` the maximum denominator
@ -33,39 +48,69 @@ The return value is an array of the form `[quot, num, den]` where `quot==0`
for improper fractions. `quot <= x` for mixed fractions, which may lead to some
unexpected results when rendering negative numbers.
### JS
The exported `frac` function implements the Mediant method.
`frac.cont` implements the Aberth algorithm
For example:
```
```js
> // var frac = require('frac'); // uncomment this line if in node
> frac(Math.PI,100); // [ 0, 22, 7 ]
> frac(Math.PI,100,true); // [ 3, 1, 7 ]
> frac(-Math.PI,100); // [ 0, -22, 7 ]
> frac(-Math.PI,100,true); // [ -4, 6, 7 ] // the approximation is (-4) + (6/7)
> frac(1.3, 9); // [ 0, 9, 7 ] // 1.3 ~ 9/7
> frac(1.3, 9, true); // [ 1, 2, 7 ] // 1.3 ~ 1 + 2/7
> frac(-1.3, 9); // [ 0, -9, 7 ] // -1.3 ~ -9/7
> frac(-1.3, 9, true); // [ -2, 5, 7 ] // -1.3 ~ -2 + 5/7
> frac.cont(1.3, 9); // [ 0, 4, 3 ] // 1.3 ~ 4/3
> frac.cont(1.3, 9, true); // [ 1, 1, 3 ] // 1.3 ~ 1 + 1/3
> frac.cont(-1.3, 9); // [ 0, -4, 3 ] // -1.3 ~ -4/3
> frac.cont(-1.3, 9, true); // [ -2, 2, 3 ] // -1.3 ~ -2 + 2/3
```
`frac.cont` implements the Aberth algorithm (input and output specifications
match the original `frac` function)
### Python
`frac.med` implements Mediant method.
`frac.cont` implements Aberth algorithm.
For example:
```py
>>> import frac
>>> frac.med(1.3, 9) ## [ 0, 9, 7 ] ## 1.3 ~ 9/7
>>> frac.med(1.3, 9, True) ## [ 1, 2, 7 ] ## 1.3 ~ 1 + 2/7
>>> frac.med(-1.3, 9) ## [ 0, -9, 7 ] ## -1.3 ~ -9/7
>>> frac.med(-1.3, 9, True) ## [ -2, 5, 7 ] ## -1.3 ~ -2 + 5/7
>>> frac.cont(1.3, 9) ## [ 0, 4, 3 ] ## 1.3 ~ 4/3
>>> frac.cont(1.3, 9, True) ## [ 1, 1, 3 ] ## 1.3 ~ 1 + 1/3
>>> frac.cont(-1.3, 9) ## [ 0, -4, 3 ] ## -1.3 ~ -4/3
>>> frac.cont(-1.3, 9, True) ## [ -2, 2, 3 ] ## -1.3 ~ -2 + 2/3
```
## Testing
`make test` will run the node-based tests.
Tests generated from Excel have 4 columns. To produce a similar test:
The test TSV baselines in the `test_files` directory have four columns:
- Column A contains the raw values
- Column B format "Up to one digit (1/4)"
- Column C format "Up to two digits (21/25)"
- Column D format "Up to three digits (312/943)"
- Column B format "Up to one digit (1/4)" (`denominator = 9`)
- Column C format "Up to two digits (21/25)" (`denominator = 99`)
- Column D format "Up to three digits (312/943)" (`denominator = 999`)
`make test` will run the node-based tests.
`make ctest` will use `browserify` to build a standalone script that can be run
in the web browser. The transform `brfs` must be installed locally. Browser
test script built against `browserify@16.5.1` and `brfs@2.0.2`.
`make pytest` will run the python tests against the system Python version.
`make pypytest` will run the python tests against `pypy` if installed
## License
Please consult the attached LICENSE file for details. All rights not explicitly
granted by the Apache 2.0 license are reserved by the Original Author.
## Badges
[![Build Status](https://travis-ci.org/SheetJS/frac.svg?branch=master)](https://travis-ci.org/SheetJS/frac)
[![Coverage Status](http://img.shields.io/coveralls/SheetJS/frac/master.svg)](https://coveralls.io/r/SheetJS/frac?branch=master)
[![githalytics.com alpha](https://cruel-carlota.pagodabox.com/731e31b3a26382ccd5d213b9e74ea552 "githalytics.com")](http://githalytics.com/SheetJS/frac)
granted by the Apache 2.0 License are reserved by the Original Author.

2
ctest/fakeassert.js Normal file

@ -0,0 +1,2 @@
var assert = {};
assert.equal = function(x,y) { if(x !== y) throw new Error(x + " !== " + y); };

40
ctest/frac.js Normal file

@ -0,0 +1,40 @@
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac = function frac(x, D, mixed) {
var n1 = Math.floor(x), d1 = 1;
var n2 = n1+1, d2 = 1;
if(x !== n1) while(d1 + d2 <= D) {
var m = (n1 + n2) / (d1 + d2);
if(x === m) {
if(d1 + d2 <= D) { d2 = (d1+=d2); n2 = (n1+=n2); }
break;
}
else if(x < m) { n2 = n1+n2; d2 = d1+d2; }
else { n1 = n1+n2; d1 = d1+d2; }
}
if(n2 / d2 - x <= x - n1 / d1 ) { d1 = d2; n1 = n2; }
if(!mixed) return [0, n1, d1];
var q = Math.floor(n1/d1);
return [q, n1 - q*d1, d1];
};
frac.cont = function cont(x, D, mixed) {
var sgn = x < 0 ? -1 : 1;
var B = x * sgn;
var P_2 = 0, P_1 = 1, P = 0;
var Q_2 = 1, Q_1 = 0, Q = 0;
var A = Math.floor(B);
while(Q_1 < D) {
A = Math.floor(B);
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
if((B - A) < 0.00000005) break;
B = 1 / (B - A);
P_2 = P_1; P_1 = P;
Q_2 = Q_1; Q_1 = Q;
}
if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
if(!mixed) return [0, sgn * P, Q];
var q = Math.floor(sgn * P/Q);
return [q, sgn*P - q*Q, Q];
};
// eslint-disable-next-line no-undef
if(typeof module !== 'undefined' && typeof DO_NOT_EXPORT_FRAC === 'undefined') module.exports = frac;

22
ctest/index.html Normal file

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<!--<script src="shim.js"></script>-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="frac.js"></script>
<script src="fakeassert.js"></script>
<script src="mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>

305
ctest/mocha.css Normal file

@ -0,0 +1,305 @@
@charset "utf-8";
body {
margin:0;
}
#mocha {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 60px 50px;
}
#mocha ul,
#mocha li {
margin: 0;
padding: 0;
}
#mocha ul {
list-style: none;
}
#mocha h1,
#mocha h2 {
margin: 0;
}
#mocha h1 {
margin-top: 15px;
font-size: 1em;
font-weight: 200;
}
#mocha h1 a {
text-decoration: none;
color: inherit;
}
#mocha h1 a:hover {
text-decoration: underline;
}
#mocha .suite .suite h1 {
margin-top: 0;
font-size: .8em;
}
#mocha .hidden {
display: none;
}
#mocha h2 {
font-size: 12px;
font-weight: normal;
cursor: pointer;
}
#mocha .suite {
margin-left: 15px;
}
#mocha .test {
margin-left: 15px;
overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
font-family: arial, sans-serif;
}
#mocha .test.pass.medium .duration {
background: #c09853;
}
#mocha .test.pass.slow .duration {
background: #b94a48;
}
#mocha .test.pass::before {
content: '✓';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #00d6b2;
}
#mocha .test.pass .duration {
font-size: 9px;
margin-left: 5px;
padding: 2px 5px;
color: #fff;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
#mocha .test.pass.fast .duration {
display: none;
}
#mocha .test.pending {
color: #0b97c4;
}
#mocha .test.pending::before {
content: '◦';
color: #0b97c4;
}
#mocha .test.fail {
color: #c00;
}
#mocha .test.fail pre {
color: black;
}
#mocha .test.fail::before {
content: '✖';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #c00;
}
#mocha .test pre.error {
color: #c00;
max-height: 300px;
overflow: auto;
}
#mocha .test .html-error {
overflow: auto;
color: black;
line-height: 1.5;
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: calc(100% - 42px); /*(2)*/
max-height: 300px;
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
border-radius: 3px;
}
#mocha .test .html-error pre.error {
border: none;
-webkit-border-radius: none;
-webkit-box-shadow: none;
-moz-border-radius: none;
-moz-box-shadow: none;
padding: 0;
margin: 0;
margin-top: 18px;
max-height: none;
}
/**
* (1): approximate for browsers not supporting calc
* (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
* ^^ seriously
*/
#mocha .test pre {
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: calc(100% - 42px); /*(2)*/
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
border-radius: 3px;
}
#mocha .test h2 {
position: relative;
}
#mocha .test a.replay {
position: absolute;
top: 3px;
right: 0;
text-decoration: none;
vertical-align: middle;
display: block;
width: 15px;
height: 15px;
line-height: 15px;
text-align: center;
background: #eee;
font-size: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-transition: opacity 200ms;
-moz-transition: opacity 200ms;
transition: opacity 200ms;
opacity: 0.3;
color: #888;
}
#mocha .test:hover a.replay {
opacity: 1;
}
#mocha-report.pass .test.fail {
display: none;
}
#mocha-report.fail .test.pass {
display: none;
}
#mocha-report.pending .test.pass,
#mocha-report.pending .test.fail {
display: none;
}
#mocha-report.pending .test.pass.pending {
display: block;
}
#mocha-error {
color: #c00;
font-size: 1.5em;
font-weight: 100;
letter-spacing: 1px;
}
#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
z-index: 1;
}
#mocha-stats .progress {
float: right;
padding-top: 0;
}
#mocha-stats em {
color: black;
}
#mocha-stats a {
text-decoration: none;
color: inherit;
}
#mocha-stats a:hover {
border-bottom: 1px solid #eee;
}
#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
#mocha-stats canvas {
width: 40px;
height: 40px;
}
#mocha code .comment { color: #ddd; }
#mocha code .init { color: #2f6fad; }
#mocha code .string { color: #5890ad; }
#mocha code .keyword { color: #8a6343; }
#mocha code .number { color: #2f6fad; }
@media screen and (max-device-width: 480px) {
#mocha {
margin: 60px 0px;
}
#mocha #stats {
position: absolute;
}
}

5842
ctest/mocha.js Normal file

File diff suppressed because it is too large Load Diff

1524
ctest/test.js Normal file

File diff suppressed because it is too large Load Diff

190
dist/LICENSE vendored

@ -1,4 +1,192 @@
Copyright (C) 2012-2015 SheetJS
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2012-present SheetJS LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

18
dist/frac.js vendored

@ -1,19 +1,17 @@
/* frac.js (C) 2012-2015 SheetJS -- http://sheetjs.com */
var frac = function(x, D, mixed) {
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac = function frac(x, D, mixed) {
var n1 = Math.floor(x), d1 = 1;
var n2 = n1+1, d2 = 1;
if(x !== n1) while(d1 <= D && d2 <= D) {
if(x !== n1) while(d1 + d2 <= D) {
var m = (n1 + n2) / (d1 + d2);
if(x === m) {
if(d1 + d2 <= D) { d1+=d2; n1+=n2; d2=D+1; }
else if(d1 > d2) d2=D+1;
else d1=D+1;
if(d1 + d2 <= D) { d2 = (d1+=d2); n2 = (n1+=n2); }
break;
}
else if(x < m) { n2 = n1+n2; d2 = d1+d2; }
else { n1 = n1+n2; d1 = d1+d2; }
}
if(d1 > D) { d1 = d2; n1 = n2; }
if(n2 / d2 - x <= x - n1 / d1 ) { d1 = d2; n1 = n2; }
if(!mixed) return [0, n1, d1];
var q = Math.floor(n1/d1);
return [q, n1 - q*d1, d1];
@ -28,15 +26,15 @@ frac.cont = function cont(x, D, mixed) {
A = Math.floor(B);
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
if((B - A) < 0.0000000005) break;
if((B - A) < 0.00000005) break;
B = 1 / (B - A);
P_2 = P_1; P_1 = P;
Q_2 = Q_1; Q_1 = Q;
}
if(Q > D) { Q = Q_1; P = P_1; }
if(Q > D) { Q = Q_2; P = P_2; }
if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
if(!mixed) return [0, sgn * P, Q];
var q = Math.floor(sgn * P/Q);
return [q, sgn*P - q*Q, Q];
};
// eslint-disable-next-line no-undef
if(typeof module !== 'undefined' && typeof DO_NOT_EXPORT_FRAC === 'undefined') module.exports = frac;

4
dist/frac.min.js vendored

@ -1,2 +1,2 @@
/* frac.js (C) 2012-2015 SheetJS -- http://sheetjs.com */
var frac=function(x,D,mixed){var n1=Math.floor(x),d1=1;var n2=n1+1,d2=1;if(x!==n1)while(d1<=D&&d2<=D){var m=(n1+n2)/(d1+d2);if(x===m){if(d1+d2<=D){d1+=d2;n1+=n2;d2=D+1}else if(d1>d2)d2=D+1;else d1=D+1;break}else if(x<m){n2=n1+n2;d2=d1+d2}else{n1=n1+n2;d1=d1+d2}}if(d1>D){d1=d2;n1=n2}if(!mixed)return[0,n1,d1];var q=Math.floor(n1/d1);return[q,n1-q*d1,d1]};frac.cont=function cont(x,D,mixed){var sgn=x<0?-1:1;var B=x*sgn;var P_2=0,P_1=1,P=0;var Q_2=1,Q_1=0,Q=0;var A=Math.floor(B);while(Q_1<D){A=Math.floor(B);P=A*P_1+P_2;Q=A*Q_1+Q_2;if(B-A<5e-10)break;B=1/(B-A);P_2=P_1;P_1=P;Q_2=Q_1;Q_1=Q}if(Q>D){Q=Q_1;P=P_1}if(Q>D){Q=Q_2;P=P_2}if(!mixed)return[0,sgn*P,Q];var q=Math.floor(sgn*P/Q);return[q,sgn*P-q*Q,Q]};if(typeof module!=="undefined"&&typeof DO_NOT_EXPORT_FRAC==="undefined")module.exports=frac;
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac=function frac(x,D,mixed){var n1=Math.floor(x),d1=1;var n2=n1+1,d2=1;if(x!==n1)while(d1+d2<=D){var m=(n1+n2)/(d1+d2);if(x===m){if(d1+d2<=D){d2=d1+=d2;n2=n1+=n2}break}else if(x<m){n2=n1+n2;d2=d1+d2}else{n1=n1+n2;d1=d1+d2}}if(n2/d2-x<=x-n1/d1){d1=d2;n1=n2}if(!mixed)return[0,n1,d1];var q=Math.floor(n1/d1);return[q,n1-q*d1,d1]};frac.cont=function cont(x,D,mixed){var sgn=x<0?-1:1;var B=x*sgn;var P_2=0,P_1=1,P=0;var Q_2=1,Q_1=0,Q=0;var A=Math.floor(B);while(Q_1<D){A=Math.floor(B);P=A*P_1+P_2;Q=A*Q_1+Q_2;if(B-A<5e-8)break;B=1/(B-A);P_2=P_1;P_1=P;Q_2=Q_1;Q_1=Q}if(Q>D){if(Q_1>D){Q=Q_2;P=P_2}else{Q=Q_1;P=P_1}}if(!mixed)return[0,sgn*P,Q];var q=Math.floor(sgn*P/Q);return[q,sgn*P-q*Q,Q]};if(typeof module!=="undefined"&&typeof DO_NOT_EXPORT_FRAC==="undefined")module.exports=frac;

2
dist/frac.min.map vendored

@ -1 +1 @@
{"version":3,"file":"dist/frac.min.js","sources":["frac.js"],"names":["frac","x","D","mixed","n1","Math","floor","d1","n2","d2","m","q","cont","sgn","B","P_2","P_1","P","Q_2","Q_1","Q","A","module","DO_NOT_EXPORT_FRAC","exports"],"mappings":";AACA,GAAIA,MAAO,SAASC,EAAGC,EAAGC,OACxB,GAAIC,IAAKC,KAAKC,MAAML,GAAIM,GAAK,CAC7B,IAAIC,IAAKJ,GAAG,EAAGK,GAAK,CACpB,IAAGR,IAAMG,GAAI,MAAMG,IAAML,GAAKO,IAAMP,EAAG,CACrC,GAAIQ,IAAKN,GAAKI,KAAOD,GAAKE,GAC1B,IAAGR,IAAMS,EAAG,CACV,GAAGH,GAAKE,IAAMP,EAAG,CAAEK,IAAIE,EAAIL,KAAII,EAAIC,IAAGP,EAAE,MACnC,IAAGK,GAAKE,GAAIA,GAAGP,EAAE,MACjBK,IAAGL,EAAE,CACV,WAEG,IAAGD,EAAIS,EAAG,CAAEF,GAAKJ,GAAGI,EAAIC,IAAKF,GAAGE,OAChC,CAAEL,GAAKA,GAAGI,EAAID,IAAKA,GAAGE,IAE7B,GAAGF,GAAKL,EAAG,CAAEK,GAAKE,EAAIL,IAAKI,GAC3B,IAAIL,MAAO,OAAQ,EAAGC,GAAIG,GAC1B,IAAII,GAAIN,KAAKC,MAAMF,GAAGG,GACtB,QAAQI,EAAGP,GAAKO,EAAEJ,GAAIA,IAExBP,MAAKY,KAAO,QAASA,MAAKX,EAAGC,EAAGC,OAC9B,GAAIU,KAAMZ,EAAI,GAAK,EAAI,CACvB,IAAIa,GAAIb,EAAIY,GACZ,IAAIE,KAAM,EAAGC,IAAM,EAAGC,EAAI,CAC1B,IAAIC,KAAM,EAAGC,IAAM,EAAGC,EAAI,CAC1B,IAAIC,GAAIhB,KAAKC,MAAMQ,EACnB,OAAMK,IAAMjB,EAAG,CACbmB,EAAIhB,KAAKC,MAAMQ,EACfG,GAAII,EAAIL,IAAMD,GACdK,GAAIC,EAAIF,IAAMD,GACd,IAAIJ,EAAIO,EAAK,MAAc,KAC3BP,GAAI,GAAKA,EAAIO,EACbN,KAAMC,GAAKA,KAAMC,CACjBC,KAAMC,GAAKA,KAAMC,EAEnB,GAAGA,EAAIlB,EAAG,CAAEkB,EAAID,GAAKF,GAAID,IACzB,GAAGI,EAAIlB,EAAG,CAAEkB,EAAIF,GAAKD,GAAIF,IACzB,IAAIZ,MAAO,OAAQ,EAAGU,IAAMI,EAAGG,EAC/B,IAAIT,GAAIN,KAAKC,MAAMO,IAAMI,EAAEG,EAC3B,QAAQT,EAAGE,IAAII,EAAIN,EAAES,EAAGA,GAE1B,UAAUE,UAAW,mBAAsBC,sBAAuB,YAAaD,OAAOE,QAAUxB"}
{"version":3,"sources":["frac.js"],"names":["frac","x","D","mixed","n1","Math","floor","d1","n2","d2","m","q","cont","sgn","B","P_2","P_1","P","Q_2","Q_1","Q","A","module","DO_NOT_EXPORT_FRAC","exports"],"mappings":";AACA,GAAIA,MAAO,QAASA,MAAKC,EAAGC,EAAGC,OAC7B,GAAIC,IAAKC,KAAKC,MAAML,GAAIM,GAAK,CAC7B,IAAIC,IAAKJ,GAAG,EAAGK,GAAK,CACpB,IAAGR,IAAMG,GAAI,MAAMG,GAAKE,IAAMP,EAAG,CAC/B,GAAIQ,IAAKN,GAAKI,KAAOD,GAAKE,GAC1B,IAAGR,IAAMS,EAAG,CACV,GAAGH,GAAKE,IAAMP,EAAG,CAAEO,GAAMF,IAAIE,EAAKD,IAAMJ,IAAII,GAC5C,UAEG,IAAGP,EAAIS,EAAG,CAAEF,GAAKJ,GAAGI,EAAIC,IAAKF,GAAGE,OAChC,CAAEL,GAAKA,GAAGI,EAAID,IAAKA,GAAGE,IAE7B,GAAGD,GAAKC,GAAKR,GAAKA,EAAIG,GAAKG,GAAK,CAAEA,GAAKE,EAAIL,IAAKI,GAChD,IAAIL,MAAO,OAAQ,EAAGC,GAAIG,GAC1B,IAAII,GAAIN,KAAKC,MAAMF,GAAGG,GACtB,QAAQI,EAAGP,GAAKO,EAAEJ,GAAIA,IAExBP,MAAKY,KAAO,QAASA,MAAKX,EAAGC,EAAGC,OAC9B,GAAIU,KAAMZ,EAAI,GAAK,EAAI,CACvB,IAAIa,GAAIb,EAAIY,GACZ,IAAIE,KAAM,EAAGC,IAAM,EAAGC,EAAI,CAC1B,IAAIC,KAAM,EAAGC,IAAM,EAAGC,EAAI,CAC1B,IAAIC,GAAIhB,KAAKC,MAAMQ,EACnB,OAAMK,IAAMjB,EAAG,CACbmB,EAAIhB,KAAKC,MAAMQ,EACfG,GAAII,EAAIL,IAAMD,GACdK,GAAIC,EAAIF,IAAMD,GACd,IAAIJ,EAAIO,EAAK,KAAY,KACzBP,GAAI,GAAKA,EAAIO,EACbN,KAAMC,GAAKA,KAAMC,CACjBC,KAAMC,GAAKA,KAAMC,EAEnB,GAAGA,EAAIlB,EAAG,CAAE,GAAGiB,IAAMjB,EAAG,CAAEkB,EAAIF,GAAKD,GAAIF,QAAY,CAAEK,EAAID,GAAKF,GAAID,KAClE,IAAIb,MAAO,OAAQ,EAAGU,IAAMI,EAAGG,EAC/B,IAAIT,GAAIN,KAAKC,MAAMO,IAAMI,EAAEG,EAC3B,QAAQT,EAAGE,IAAII,EAAIN,EAAES,EAAGA,GAG1B,UAAUE,UAAW,mBAAsBC,sBAAuB,YAAaD,OAAOE,QAAUxB","file":"dist/frac.min.js"}

@ -1,19 +1,17 @@
/* frac.js (C) 2012-2015 SheetJS -- http://sheetjs.com */
var frac = function(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac = function frac(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
var n1 = Math.floor(x), d1 = 1;
var n2 = n1+1, d2 = 1;
if(x !== n1) while(d1 <= D && d2 <= D) {
if(x !== n1) while(d1 + d2 <= D) {
var m = (n1 + n2) / (d1 + d2);
if(x === m) {
if(d1 + d2 <= D) { d1+=d2; n1+=n2; d2=D+1; }
else if(d1 > d2) d2=D+1;
else d1=D+1;
if(d1 + d2 <= D) { d2 = (d1+=d2); n2 = (n1+=n2); }
break;
}
else if(x < m) { n2 = n1+n2; d2 = d1+d2; }
else { n1 = n1+n2; d1 = d1+d2; }
}
if(d1 > D) { d1 = d2; n1 = n2; }
if(n2 / d2 - x <= x - n1 / d1 ) { d1 = d2; n1 = n2; }
if(!mixed) return [0, n1, d1];
var q = Math.floor(n1/d1);
return [q, n1 - q*d1, d1];
@ -28,16 +26,16 @@ frac.cont = function cont(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Arra
A = Math.floor(B);
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
if((B - A) < 0.0000000005) break;
if((B - A) < 0.00000005) break;
B = 1 / (B - A);
P_2 = P_1; P_1 = P;
Q_2 = Q_1; Q_1 = Q;
}
if(Q > D) { Q = Q_1; P = P_1; }
if(Q > D) { Q = Q_2; P = P_2; }
if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
if(!mixed) return [0, sgn * P, Q];
var q = Math.floor(sgn * P/Q);
return [q, sgn*P - q*Q, Q];
};
/*:: declare var DO_NOT_EXPORT_FRAC: any; */
// eslint-disable-next-line no-undef
if(typeof module !== 'undefined' && typeof DO_NOT_EXPORT_FRAC === 'undefined') module.exports = frac;

18
frac.js

@ -1,19 +1,17 @@
/* frac.js (C) 2012-2015 SheetJS -- http://sheetjs.com */
var frac = function(x, D, mixed) {
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac = function frac(x, D, mixed) {
var n1 = Math.floor(x), d1 = 1;
var n2 = n1+1, d2 = 1;
if(x !== n1) while(d1 <= D && d2 <= D) {
if(x !== n1) while(d1 + d2 <= D) {
var m = (n1 + n2) / (d1 + d2);
if(x === m) {
if(d1 + d2 <= D) { d1+=d2; n1+=n2; d2=D+1; }
else if(d1 > d2) d2=D+1;
else d1=D+1;
if(d1 + d2 <= D) { d2 = (d1+=d2); n2 = (n1+=n2); }
break;
}
else if(x < m) { n2 = n1+n2; d2 = d1+d2; }
else { n1 = n1+n2; d1 = d1+d2; }
}
if(d1 > D) { d1 = d2; n1 = n2; }
if(n2 / d2 - x <= x - n1 / d1 ) { d1 = d2; n1 = n2; }
if(!mixed) return [0, n1, d1];
var q = Math.floor(n1/d1);
return [q, n1 - q*d1, d1];
@ -28,15 +26,15 @@ frac.cont = function cont(x, D, mixed) {
A = Math.floor(B);
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
if((B - A) < 0.0000000005) break;
if((B - A) < 0.00000005) break;
B = 1 / (B - A);
P_2 = P_1; P_1 = P;
Q_2 = Q_1; Q_1 = Q;
}
if(Q > D) { Q = Q_1; P = P_1; }
if(Q > D) { Q = Q_2; P = P_2; }
if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
if(!mixed) return [0, sgn * P, Q];
var q = Math.floor(sgn * P/Q);
return [q, sgn*P - q*Q, Q];
};
// eslint-disable-next-line no-undef
if(typeof module !== 'undefined' && typeof DO_NOT_EXPORT_FRAC === 'undefined') module.exports = frac;

117
frac.md

@ -22,8 +22,8 @@ fractions. Some interpret `a b/c` as `sgn(a) * [abs(a) + b/c]`. To replicate
that behavior, pass the absolute value to frac and prepend a "-" if negative.
```js>frac.flow.js
/* frac.js (C) 2012-2015 SheetJS -- http://sheetjs.com */
var frac = function(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
var frac = function frac(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
```
The goal is to maintain a feasible fraction (with bounded denominator) below
@ -36,14 +36,14 @@ the numerators and denominators separately:
var n2 = n1+1, d2 = 1;
```
If `x` is not integral, we bisect using mediants until a denominator exceeds
our target:
If `x` is not integral, we bisect using mediants until a the next denominator
exceeds our target:
```
if(x !== n1) while(d1 <= D && d2 <= D) {
if(x !== n1) while(d1 + d2 <= D) {
```
The mediant is the sum of the numerators divided by the sum of demoninators:
The mediant is the sum of the numerators divided by the sum of denominators:
```
var m = (n1 + n2) / (d1 + d2);
@ -55,9 +55,7 @@ denominator)
```
if(x === m) {
if(d1 + d2 <= D) { d1+=d2; n1+=n2; d2=D+1; }
else if(d1 > d2) d2=D+1;
else d1=D+1;
if(d1 + d2 <= D) { d2 = (d1+=d2); n2 = (n1+=n2); }
break;
}
```
@ -70,11 +68,17 @@ Otherwise shrink the range:
}
```
At this point, `d1 > D` or `d2 > D` (but not both -- keep track of how `d1` and
`d2` change). So we merely return the desired values:
At this point, the optimal fraction is either `n1 / d1` or `n2 / d2`. The deltas
should be compared to determine the closer fraction. For this function, we will
store the results in `n1` and `d1`:
```
if(n2 / d2 - x <= x - n1 / d1 ) { d1 = d2; n1 = n2; }
```
The rest of the function determines which fraction to return:
```
if(d1 > D) { d1 = d2; n1 = n2; }
if(!mixed) return [0, n1, d1];
var q = Math.floor(n1/d1);
return [q, n1 - q*d1, d1];
@ -91,7 +95,7 @@ to the desired goal of most accurately approximating the floating point number)
frac.cont = function cont(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
```
> Record the sign of x, take b0=|x|, p_{-2}=0, p_{-1}=1, q_{-2}=1, q_{-1}=0
> Record the sign of x, take `b0=|x|, p_{-2}=0, p_{-1}=1, q_{-2}=1, q_{-1}=0`
Note that the variables are implicitly indexed at `k` (so `B` refers to `b_k`):
@ -102,8 +106,8 @@ Note that the variables are implicitly indexed at `k` (so `B` refers to `b_k`):
var Q_2 = 1, Q_1 = 0, Q = 0;
```
`A` should be the floor of `B`. Originally the bit-or trick was used, but this is not correct
for the range `B>=2**32`.
`A` should be the floor of `B`. Originally the bit-or trick was used, but this
is not correct for the range `B>=2**32`.
```
var A = Math.floor(B);
@ -111,31 +115,31 @@ for the range `B>=2**32`.
> Iterate
> ... for k = 0,1,...,K, where K is the first instance of k where
> either q_{k+1} > Q or b_{k+1} is undefined (b_k = a_k).
> ... for `k = 0,1,...,K`, where `K` is the first instance of `k` where
> either `q_{k+1} > Q` or `b_{k+1}` is undefined (`b_k = a_k`).
```
while(Q_1 < D) {
```
> a_k = [b_k], i.e., the greatest integer <= b_k
> `a_k = [b_k]`, the greatest integer `<= b_k`
```
A = Math.floor(B);
```
> p_k = a_k p_{k-1} + p_{k-2}
> q_k = a_k q_{k-1} + q_{k-2}
> `p_k = a_k p_{k-1} + p_{k-2}`
> `q_k = a_k q_{k-1} + q_{k-2}`
```
P = A * P_1 + P_2;
Q = A * Q_1 + Q_2;
```
> b_{k+1} = (b_{k} - a_{k})^{-1}
> `b_{k+1} = (b_{k} - a_{k})^{-1}`
```
if((B - A) < 0.0000000005) break;
if((B - A) < 0.00000005) break;
```
At the end of each iteration, advance `k` by one step:
@ -147,11 +151,10 @@ At the end of each iteration, advance `k` by one step:
}
```
In case we end up overstepping, walk back an iteration or two:
In case we end up overstepping, walk back to the last valid iteration:
```
if(Q > D) { Q = Q_1; P = P_1; }
if(Q > D) { Q = Q_2; P = P_2; }
if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
```
The final result is `r = (sgn x)p_k / q_k`:
@ -167,12 +170,14 @@ Finally we put some export jazz:
```
/*:: declare var DO_NOT_EXPORT_FRAC: any; */
// eslint-disable-next-line no-undef
if(typeof module !== 'undefined' && typeof DO_NOT_EXPORT_FRAC === 'undefined') module.exports = frac;
```
# Tests
```js>test.js
/* eslint-env mocha, node */
var fs = require('fs'), assert = require('assert');
var frac;
describe('source', function() { it('should load', function() { frac = require('./'); }); });
@ -185,24 +190,27 @@ var xltestfiles=[
];
function xlline(o,j,m,w) {
it(j, function(done) {
var d, q, qq;
it(j.toString(), function() {
var d, q, qq, f = 0.1;
var q0 = 0, q1 = 0, q2 = 0;
for(var i = j*w; i < m-3 && i < (j+1)*w; ++i) {
d = o[i].split("\t");
if(d.length < 3) continue;
f = parseFloat(d[0]);
q = frac.cont(Number(d[0]), 9, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? q[1] + "/" + q[2] : " ") : "0 ";
q = frac.cont(f, 9, true);
q0 = q[0]; q1 = q[1]; q2 = q[2];
qq = (q0!=0||q1!=0) ? (q0!=0 ? q0.toString() : "") + " " + (q1!=0 ? q1.toString() + "/" + q2.toString() : " ") : "0 ";
assert.equal(qq, d[1], d[1] + " 1");
q = frac.cont(Number(d[0]), 99, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? (q[1] < 10 ? " " : "") + q[1] + "/" + q[2] + (q[2]<10?" ":"") : " ") : "0 ";
q = frac.cont(f, 99, true);
qq = (q[0]!=0||q[1]!=0) ? (q[0]!=0 ? q[0].toString() : "") + " " + (q[1]!=0 ? (q[1] < 10 ? " " : "") + q[1].toString() + "/" + q[2].toString() + (q[2]<10?" ":"") : " ") : "0 ";
assert.equal(qq, d[2], d[2] + " 2");
q = frac.cont(Number(d[0]), 999, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? (q[1] < 100 ? " " : "") + (q[1] < 10 ? " " : "") + q[1] + "/" + q[2] + (q[2]<10?" ":"") + (q[2]<100?" ":""): " ") : "0 ";
q = frac.cont(f, 999, true);
qq = (q[0]!=0||q[1]!=0) ? (q[0]!=0 ? q[0].toString() : "") + " " + (q[1]!=0 ? (q[1] < 100 ? " " : "") + (q[1] < 10 ? " " : "") + q[1].toString() + "/" + q[2].toString() + (q[2]<10?" ":"") + (q[2]<100?" ":""): " ") : "0 ";
assert.equal(qq, d[3], d[3] + " 3");
}
done();
});
}
function parsexl(f,w) {
@ -226,6 +234,8 @@ describe('mediant', function() {
cmp(frac(1.0,9,true), [1,0,1]);
cmp(frac(1.7,9,true), [1,5,7]);
cmp(frac(1.7,9,false),[0,12,7]);
cmp(frac(0.69,9,false),[0,2,3]);
cmp(frac(0.6969,9,false),[0,5,7]);
});
});
xltestfiles.forEach(function(x) {
@ -241,27 +251,38 @@ xltestfiles.forEach(function(x) {
```json>package.json
{
"name": "frac",
"version": "1.0.1",
"version": "1.1.3",
"author": "SheetJS",
"description": "Rational approximation with bounded denominator",
"keywords": [ "math", "fraction", "rational", "approximation" ],
"main": "frac.js",
"dependencies": {
"voc":""
},
"main": "./frac",
"types": "types",
"dependencies": {},
"devDependencies": {
"mocha":""
"voc": "~1.1.0",
"mocha": "~2.5.3",
"blanket": "~1.2.3",
"codepage": "~1.10.0",
"@sheetjs/uglify-js": "~2.7.3",
"@types/node": "^8.0.7",
"brfs": "^2.0.2",
"dtslint": "^0.1.2",
"typescript": "2.2.0"
},
"repository": { "type":"git", "url":"git://github.com/SheetJS/frac.git" },
"repository": { "type": "git", "url": "https://git.sheetjs.com/SheetJS/frac.git" },
"scripts": {
"test": "mocha -R spec"
"test": "make test",
"build": "make",
"lint": "make fullint",
"dtslint": "dtslint types"
},
"config": {
"blanket": {
"pattern": "frac.js"
}
},
"bugs": { "url": "https://github.com/SheetJS/frac/issues" },
"homepage": "http://sheetjs.com/opensource",
"bugs": { "url": "https://git.sheetjs.com/SheetJS/frac/issues" },
"license": "Apache-2.0",
"engines": { "node": ">=0.8" }
}
@ -270,11 +291,18 @@ xltestfiles.forEach(function(x) {
And to make sure that test files are not included in npm:
```>.npmignore
frac.flow.js
frac.md
test_files/*.tsv
ctest/
test.js
Makefile
.gitignore
.npmignore
node_modules/
coverage.html
.travis.yml
.eslintrc
.jshintrc
.jscs.json
.flowconfig
@ -285,6 +313,9 @@ build/
MANIFEST
*.gz
*.tgz
*.py
*.html
.spelling
```
Don't include the node modules in git:

26
frac.py

@ -1,4 +1,4 @@
# frac.py (C) 2015 SheetJS -- http://sheetjs.com
# frac.py (C) 2015-present SheetJS -- http://sheetjs.com
# vim: set fileencoding=utf-8 :
"""
Rational approximations to numbers
@ -16,18 +16,16 @@ All functions take 3 arguments:
The return value is a list of 3 elements: [quotient, numerator, denominator]
"""
import math as Math
def med(x, D, mixed=False):
"""Generate fraction representation using Mediant method"""
n1, d1 = int(Math.floor(x)), 1
n1, d1 = int(x), 1
n2, d2 = n1+1, 1
m = 0.
if x != n1:
while d1 <= D and d2 <= D:
m = float(n1 + n2) / (d1 + d2)
if(x == m):
if x == m:
if d1 + d2 <= D:
n1, d1 = n1 + n2, d1 + d2
d2 = D + 1
@ -50,23 +48,23 @@ def med(x, D, mixed=False):
def cont(x, D, mixed=False):
"""Generate fraction representation using Aberth method"""
sgn = -1 if x < 0 else 1
B = abs(x)
P_2, P_1, P = 0, 1, 0
Q_2, Q_1, Q = 1, 0, 0
P_2, P_1, P, Q_2, Q_1, Q = 0, 1, 0, 1, 0, 0
while Q_1 < D:
A = int(Math.floor(B))
A = int(B)
P = A * P_1 + P_2
Q = A * Q_1 + Q_2
if ((B - A) < 0.0000000005):
if (B - A) < 0.00000005:
break
B = 1. / (B-A)
P_2, P_1 = P_1, P
Q_2, Q_1 = Q_1, Q
if(Q > D):
P, Q = P_1, Q_1
if(Q > D):
P, Q = P_2, Q_2
if Q > D:
if Q_1 <= D:
P, Q = P_1, Q_1
else:
P, Q = P_2, Q_2
sgn = -1 if x < 0 else 1
if not mixed:
return [0, sgn * P, Q]
q = divmod(sgn * P, Q)

@ -1,79 +1,86 @@
<!DOCTYPE html>
<!-- frac.js (C) 2015 SheetJS http://sheetjs.com -->
<!-- frac.js (C) 2012-present SheetJS http://sheetjs.com -->
<!-- vim: set ts=2: -->
<html>
<head>
<title>Fraction Live Demo</title>
<script src="frac.js"></script>
</head>
<body>
<b>Fraction Live Demo</b><br />
<a href="https://github.com/SheetJS/frac">Source Code</a><br />
<a href="https://github.com/SheetJS/frac/issues">Issues? Something look weird? Click here and report an issue</a><br />
<br />
<table>
<tr><td><b>Number:</b></td><td><input type="text" id="val" value="1.3"></td></tr>
<tr><td><b>Denominator Digits:</b></td><td><input type="text" id="fmt" value="1"></td></tr>
<tr><td><b>Use Mixed Fraction:</b></td><td><input type="checkbox" id="mix" name="mixd" checked></td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td><b>Mediant Fraction:</b></td><td><pre id="frm"></pre></td></tr>
<tr><td><b>Aberth Fraction:</b></td><td><pre id="fra"></pre></td></tr>
</table>
</body>
<script>
var V = document.getElementById('val');
var F = document.getElementById('fmt');
var X = document.getElementById('mix');
var M = document.getElementById('frm');
var A = document.getElementById('fra');
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Fraction Live Demo</title>
<style>
a { text-decoration: none }
</style>
</head>
<body>
<pre>
<b><a href="http://sheetjs.com">SheetJS Fraction Live Demo</a></b>
function update() {
var x, D, mixed, oM, oA;
x = Number(V.value);
D = Math.pow(10, Number(F.value))-1;
mixed = X.checked;
if(x !== x) { M.innerHTML=A.innerHTML = V.value + " not valid"; return; }
if(D !== D) { M.innerHTML=A.innerHTML = F.value + " not valid"; return; }
try {
oM = frac(x, D, mixed);
M.innerHTML = oM[0] + " " + oM[1] + "/" + oM[2];
} catch(e) { M.innerHTML = e.message; }
try {
oA = frac.cont(x, D, mixed);
A.innerHTML = oA[0] + " " + oA[1] + "/" + oA[2];
} catch(e) { A.innerHTML = e.message; }
}
<a href="https://github.com/SheetJS/frac">Source Code Repo</a>
<a href="https://github.com/SheetJS/frac/issues">Issues? Something look weird? Click here and report an issue</a>
</pre>
<table>
<tr><td><b>Number:</b></td><td><input type="text" id="val" value="1.3"></td></tr>
<tr><td><b>Denominator Digits:</b></td><td><input type="text" id="fmt" value="1"></td></tr>
<tr><td><b>Use Mixed Fraction:</b></td><td><input type="checkbox" id="mix" name="mixd" checked></td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td><b>Mediant Fraction:</b></td><td><pre id="frm"></pre></td></tr>
<tr><td><b>Aberth Fraction:</b></td><td><pre id="fra"></pre></td></tr>
</table>
<script src="frac.js"></script>
<script>
/*jshint browser:true */
/* eslint-env browser */
/* eslint no-use-before-define:0 */
/*global frac */
var V = document.getElementById('val');
var F = document.getElementById('fmt');
var X = document.getElementById('mix');
var M = document.getElementById('frm');
var A = document.getElementById('fra');
/* Bind to relevant events */
if(F.addEventListener) {
F.addEventListener('keyup', update);
V.addEventListener('keyup', update);
M.addEventListener('change', update);
X.addEventListener('change', update);
} else if(F.attachEvent) {
F.attachEvent('onkeyup', update);
V.attachEvent('onkeyup', update);
M.attachEvent('onchange', update);
X.attachEvent('onchange', update);
} else {
F.oninput = update;
V.oninput = update;
M.onchange = update;
X.onchange = update;
}
function update() {
var x, D, mixed, oM, oA;
x = Number(V.value);
D = Math.pow(10, Number(F.value))-1;
mixed = X.checked;
if(x !== x) { M.innerHTML=A.innerHTML = V.value + " not valid"; return; }
if(D !== D) { M.innerHTML=A.innerHTML = F.value + " not valid"; return; }
try {
oM = frac(x, D, mixed);
M.innerHTML = oM[0] + " " + oM[1] + "/" + oM[2];
} catch(e) { M.innerHTML = e.message; }
try {
oA = frac.cont(x, D, mixed);
A.innerHTML = oA[0] + " " + oA[1] + "/" + oA[2];
} catch(e) { A.innerHTML = e.message; }
}
update();
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36810333-1']);
_gaq.push(['_trackPageview']);
/* Bind to relevant events */
if(F.addEventListener) {
F.addEventListener('keyup', update);
V.addEventListener('keyup', update);
M.addEventListener('change', update);
X.addEventListener('change', update);
} else if(F.attachEvent) {
F.attachEvent('onkeyup', update);
V.attachEvent('onkeyup', update);
M.attachEvent('onchange', update);
X.attachEvent('onchange', update);
} else {
F.oninput = update;
V.oninput = update;
M.onchange = update;
X.onchange = update;
}
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
update();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36810333-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>

42
misc/help.sh Executable file

@ -0,0 +1,42 @@
#!/bin/bash
# make_help.sh -- process listing of targets and special items in Makefile
# Copyright (C) 2016-present SheetJS
#
# usage in makefile: pipe the output of the following command:
# @grep -hE '(^[a-zA-Z_-][ a-zA-Z_-]*:.*?|^#[#*])' $(MAKEFILE_LIST)
#
# lines starting with "## " are treated as subtitles
# lines starting with "#* " are treated as plaintext comments
# multiple targets with "## " after the ":" are rendered as separate targets
# if the presumed default target is labeled, it will be assigned a unique color
awk '
BEGIN{recipes=0;}
!/#[#*] .*$/ {next;}
{multi=0; isrecipe=0;}
/^[^#]*:/ {isrecipe=1; ++recipes;}
/^[^ :]* .*:/ {multi=1}
multi==0 && isrecipe>0 { if(recipes > 1) print; else print $0, "[default]"; next}
isrecipe == 0 {print; next}
multi>0 {
k=split($0, msg, "##"); m=split($0, a, ":"); n=split(a[1], b, " ");
for(i=1; i<=n; ++i) print b[i] ":", "##" msg[2], (recipes==1 && i==1 ? "[default]" : "")
}
END {}
' | if [[ -t 1 ]]; then
awk '
BEGIN {FS = ":.*?## "}
{color=36}
/\[default\]/ {color=35}
NF==1 && /^##/ {color=34}
NF==1 && /^#\*/ {color=20; $1 = substr($1, 4)}
{printf "\033[" color "m%-20s\033[0m %s\n", $1, $2;}
END{}' -
else
awk '
BEGIN {FS = ":.*?## "}
/^#\* / {$1 = substr($1, 4)}
{printf "%-20s %s\n", $1, $2;}
END{}' -
fi

@ -1,6 +1,6 @@
#!/bin/bash
# spin.sh -- show a spinner (for coverage test)
# Copyright (C) 2014-2015 SheetJS
# Copyright (C) 2014-present SheetJS
wpid=$1
delay=1

@ -1,6 +1,6 @@
#!/bin/bash
# strip_sourcemap.sh -- strip sourcemaps from a JS file (missing from uglifyjs)
# Copyright (C) 2014-2015 SheetJS
# Copyright (C) 2014-present SheetJS
if [ $# -gt 0 ]; then
if [ -e "$1" ]; then

@ -1,26 +1,37 @@
{
"name": "frac",
"version": "1.0.1",
"version": "1.1.3",
"author": "SheetJS",
"description": "Rational approximation with bounded denominator",
"keywords": [ "math", "fraction", "rational", "approximation" ],
"main": "frac.js",
"dependencies": {
"voc":""
},
"main": "./frac",
"types": "types",
"dependencies": {},
"devDependencies": {
"mocha":""
"voc": "~1.1.0",
"mocha": "~2.5.3",
"blanket": "~1.2.3",
"codepage": "~1.10.0",
"@sheetjs/uglify-js": "~2.7.3",
"@types/node": "^8.0.7",
"brfs": "^2.0.2",
"dtslint": "^0.1.2",
"typescript": "2.2.0"
},
"repository": { "type":"git", "url":"git://github.com/SheetJS/frac.git" },
"repository": { "type": "git", "url": "https://git.sheetjs.com/SheetJS/frac.git" },
"scripts": {
"test": "mocha -R spec"
"test": "make test",
"build": "make",
"lint": "make fullint",
"dtslint": "dtslint types"
},
"config": {
"blanket": {
"pattern": "frac.js"
}
},
"bugs": { "url": "https://github.com/SheetJS/frac/issues" },
"homepage": "http://sheetjs.com/opensource",
"bugs": { "url": "https://git.sheetjs.com/SheetJS/frac/issues" },
"license": "Apache-2.0",
"engines": { "node": ">=0.8" }
}

@ -1,7 +1,7 @@
from distutils.core import setup
setup(
name='frac',
version='0.0.1',
version='1.1.2',
author='SheetJS',
author_email='dev@sheetjs.com',
url='http://oss.sheetjs.com/frac',
@ -20,9 +20,10 @@ This module can generate fraction representations using:
license = "Apache-2.0",
keywords = ['frac', 'fraction', 'rational', 'approximation'],
classifiers = [
'Development Status :: 3 - Alpha',
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Topic :: Office/Business',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Utilities',
]
)

24
test.js

@ -1,3 +1,4 @@
/* eslint-env mocha, node */
var fs = require('fs'), assert = require('assert');
var frac;
describe('source', function() { it('should load', function() { frac = require('./'); }); });
@ -10,24 +11,27 @@ var xltestfiles=[
];
function xlline(o,j,m,w) {
it(j, function(done) {
var d, q, qq;
it(j.toString(), function() {
var d, q, qq, f = 0.1;
var q0 = 0, q1 = 0, q2 = 0;
for(var i = j*w; i < m-3 && i < (j+1)*w; ++i) {
d = o[i].split("\t");
if(d.length < 3) continue;
f = parseFloat(d[0]);
q = frac.cont(Number(d[0]), 9, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? q[1] + "/" + q[2] : " ") : "0 ";
q = frac.cont(f, 9, true);
q0 = q[0]; q1 = q[1]; q2 = q[2];
qq = (q0!=0||q1!=0) ? (q0!=0 ? q0.toString() : "") + " " + (q1!=0 ? q1.toString() + "/" + q2.toString() : " ") : "0 ";
assert.equal(qq, d[1], d[1] + " 1");
q = frac.cont(Number(d[0]), 99, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? (q[1] < 10 ? " " : "") + q[1] + "/" + q[2] + (q[2]<10?" ":"") : " ") : "0 ";
q = frac.cont(f, 99, true);
qq = (q[0]!=0||q[1]!=0) ? (q[0]!=0 ? q[0].toString() : "") + " " + (q[1]!=0 ? (q[1] < 10 ? " " : "") + q[1].toString() + "/" + q[2].toString() + (q[2]<10?" ":"") : " ") : "0 ";
assert.equal(qq, d[2], d[2] + " 2");
q = frac.cont(Number(d[0]), 999, true);
qq = (q[0]||q[1]) ? (q[0] || "") + " " + (q[1] ? (q[1] < 100 ? " " : "") + (q[1] < 10 ? " " : "") + q[1] + "/" + q[2] + (q[2]<10?" ":"") + (q[2]<100?" ":""): " ") : "0 ";
q = frac.cont(f, 999, true);
qq = (q[0]!=0||q[1]!=0) ? (q[0]!=0 ? q[0].toString() : "") + " " + (q[1]!=0 ? (q[1] < 100 ? " " : "") + (q[1] < 10 ? " " : "") + q[1].toString() + "/" + q[2].toString() + (q[2]<10?" ":"") + (q[2]<100?" ":""): " ") : "0 ";
assert.equal(qq, d[3], d[3] + " 3");
}
done();
});
}
function parsexl(f,w) {
@ -51,6 +55,8 @@ describe('mediant', function() {
cmp(frac(1.0,9,true), [1,0,1]);
cmp(frac(1.7,9,true), [1,5,7]);
cmp(frac(1.7,9,false),[0,12,7]);
cmp(frac(0.69,9,false),[0,2,3]);
cmp(frac(0.6969,9,false),[0,5,7]);
});
});
xltestfiles.forEach(function(x) {

105
test_all.py Normal file

@ -0,0 +1,105 @@
import frac
import pytest
xltestfiles = [
['xl.00001.tsv', 10000],
['xl.0001.tsv', 10000],
['xl.001.tsv', 10000],
['xl.01.tsv', 10000],
['oddities.tsv', 25]
]
mediant_tests = [
[0.1, 9, False, 0, 1, 9],
[0.2, 9, False, 0, 1, 5],
[0.3, 9, False, 0, 2, 7],
[0.4, 9, False, 0, 2, 5],
[0.5, 9, False, 0, 1, 2],
[0.6, 9, False, 0, 3, 5],
[0.7, 9, False, 0, 5, 7],
[0.8, 9, False, 0, 4, 5],
[0.9, 9, False, 0, 8, 9],
[1.0, 9, False, 0, 1, 1],
[1.0, 9, True, 1, 0, 1],
[1.7, 9, True, 1, 5, 7],
[1.7, 9, False, 0, 12, 7]
]
def test_mediant_tenths():
for t in mediant_tests:
assert frac.med(t[0], t[1], t[2]) == [t[3], t[4], t[5]]
def make9(q):
S = str
if q[0] or q[1]:
qq = (S(q[0]) if q[0] else "")
qq += " "
qq += ("/".join([S(q[1]), S(q[2])]) if q[1] else " ")
return qq
else:
return "0 "
def make99(q):
S = str
if q[0] or q[1]:
qq = (S(q[0]) if q[0] else "")
qq += " "
if q[1]:
if q[1] < 10:
qq += " "
qq += ("/".join([S(q[1]), S(q[2])]))
if q[2] < 10:
qq += " "
else:
qq += " "
return qq
else:
return "0 "
def make999(q):
S = str
if q[0] or q[1]:
qq = (S(q[0]) if q[0] else "")
qq += " "
if q[1]:
if q[1] < 10:
qq += " "
elif q[1] < 100:
qq += " "
qq += "/".join([S(q[1]), S(q[2])])
if q[2] < 10:
qq += " "
elif q[2] < 100:
qq += " "
else:
qq += " "
return qq
else:
return "0 "
def xlline(o, j, m, w):
for i in xrange(j*w, min(m-3, (j+1) * w)):
d = o[i].split("\t")
dd = float(d[0])
assert make9(frac.cont(dd, 9, True)) == d[1]
assert make99(frac.cont(dd, 99, True)) == d[2]
assert make999(frac.cont(dd, 999, True)) == d[3]
def parsexl(f, w):
oo = open(f)
d = oo.readlines()
o = filter(lambda x: len(x) > 0, map(lambda x: x.strip("\n"), d))
m = len(o)-3
for j in xrange(int(m/w)):
xlline(o, j, m, w)
@pytest.mark.parametrize("filename,step", xltestfiles)
def test_file(filename, step):
parsexl('./test_files/' + filename, step)

@ -123,4 +123,3 @@
1234567892.2 1234567892 1/5 1234567892 1/5 1234567892 1/5
1234567892.3 1234567892 2/7 1234567892 3/10 1234567892 3/10
1234567892.4 1234567892 2/5 1234567892 2/5 1234567892 2/5

1 12345678900000 12345678900000 12345678900000 12345678900000
123 1234567892.2 1234567892 1/5 1234567892 1/5 1234567892 1/5
124 1234567892.3 1234567892 2/7 1234567892 3/10 1234567892 3/10
125 1234567892.4 1234567892 2/5 1234567892 2/5 1234567892 2/5

1
types/.npmignore Normal file

@ -0,0 +1 @@
frac-test.ts

12
types/frac-test.ts Normal file

@ -0,0 +1,12 @@
import frac from 'frac';
type RV = [number, number, number];
const x1: RV = frac(1.3, 9);
const x2: RV = frac(1.3, 9, true);
const x3: RV = frac(-1.3, 9);
const x4: RV = frac(-1.3, 9, true);
const y1: RV = frac.cont(1.3, 9);
const y2: RV = frac.cont(1.3, 9, true);
const y3: RV = frac.cont(-1.3, 9);
const y4: RV = frac.cont(-1.3, 9, true);

9
types/index.d.ts vendored Normal file

@ -0,0 +1,9 @@
/* frac.js (C) 2012-present SheetJS -- http://sheetjs.com */
// TypeScript Version: 2.2
export interface Frac$Module {
(x: number, D: number, mixed?: boolean): [number, number, number];
cont(x: number, D: number, mixed?: boolean): [number, number, number];
}
export const frac: Frac$Module;
export default frac;

15
types/tsconfig.json Normal file

@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [ "es5" ],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": ".",
"paths": { "frac": ["."] },
"types": [],
"noEmit": true,
"strictFunctionTypes": true,
"forceConsistentCasingInFileNames": true
}
}

14
types/tslint.json Normal file

@ -0,0 +1,14 @@
{
"extends": "dtslint/dtslint.json",
"rules": {
"no-implicit-dependencies": false,
"whitespace": false,
"no-sparse-arrays": false,
"only-arrow-functions": false,
"no-consecutive-blank-lines": false,
"prefer-conditional-expression": false,
"one-variable-per-declaration": false,
"strict-export-declare-modifiers": false,
"prefer-template": false
}
}