repo
string
commit
string
message
string
diff
string
jquery/sizzle
11767a18f778c8a237d4b055dc1c33db4e0e22de
Selector: Detect incorrect escape handling by old Firefox
diff --git a/dist/sizzle.js b/dist/sizzle.js index f411ff8..db5ac77 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -1,1360 +1,1366 @@ /*! * Sizzle CSS Selector Engine v2.3.5-pre * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * - * Date: 2019-07-02 + * Date: 2019-08-20 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; return nonHex ? // Strip the backslash prefix from a non-hex escape sequence nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = "#" + nid + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + + // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains( preferredDoc, a ) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first ap[ i ] === preferredDoc ? -1 : bp[ i ] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } diff --git a/dist/sizzle.min.js b/dist/sizzle.min.js index db8e8bb..dd8d4dd 100644 --- a/dist/sizzle.min.js +++ b/dist/sizzle.min.js @@ -1,3 +1,3 @@ /*! Sizzle v2.3.5-pre | (c) JS Foundation and other contributors | js.foundation */ -!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),A=ae(),S=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){S(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!S[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){S(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=A[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=A(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); +!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),A=ae(),S=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){S(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("\\\f"),m.push("[\\r\\n\\f]"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!S[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){S(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=A[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=A(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); //# sourceMappingURL=sizzle.min.map \ No newline at end of file diff --git a/dist/sizzle.min.map b/dist/sizzle.min.map index be859bd..e87dec3 100644 --- a/dist/sizzle.min.map +++ b/dist/sizzle.min.map @@ -1 +1 @@ -{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","escape","nonHex","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","_argument","last","simple","forward","ofType","_context","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","_matchIndexes","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","_name","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GA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AMjK,EAAKuI,iBAAkByB,KAAYC,EAAIE,UAC9CF,EAAIrE,MACJ,OAML,IAAIwN,GAAU9V,EAAOsG,OAErBA,GAAOyP,WAAa,WAKnB,OAJK/V,EAAOsG,SAAWA,KACtBtG,EAAOsG,OAASwP,IAGVxP,IAGe,mBAAX0P,QAAyBA,OAAOC,IAC3CD,OAAQ,WACP,OAAO1P,KAIqB,oBAAX4P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU7P,GAEjBtG,EAAOsG,OAASA,GA50EjB,CAi1EKtG","file":"sizzle.min.js"} \ No newline at end of file +{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","escape","nonHex","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","_argument","last","simple","forward","ofType","_context","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","_matchIndexes","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","_name","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EA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C5B,OAAOjD,EAAKmT,eAOTlN,GAAQ,SAAUC,GACvB,OAAwC,MAAjCA,EAAGnB,aAAc,eAExBsB,GAAWlG,EAAU,SAAUH,EAAMgK,EAAMrM,GAC1C,IAAIsM,EACJ,IAAMtM,EACL,OAAwB,IAAjBqC,EAAMgK,GAAkBA,EAAK/G,eACjCgH,EAAMjK,EAAKuI,iBAAkByB,KAAYC,EAAIE,UAC9CF,EAAIrE,MACJ,OAML,IAAIwN,GAAU9V,EAAOsG,OAErBA,GAAOyP,WAAa,WAKnB,OAJK/V,EAAOsG,SAAWA,KACtBtG,EAAOsG,OAASwP,IAGVxP,IAGe,mBAAX0P,QAAyBA,OAAOC,IAC3CD,OAAQ,WACP,OAAO1P,KAIqB,oBAAX4P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU7P,GAEjBtG,EAAOsG,OAASA,GAl1EjB,CAu1EKtG","file":"sizzle.min.js"} \ No newline at end of file diff --git a/src/sizzle.js b/src/sizzle.js index 7841b98..b6c2837 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -337,1024 +337,1030 @@ function Sizzle( selector, context, results, seed ) { } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = "#" + nid + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + + // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains( preferredDoc, a ) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first ap[ i ] === preferredDoc ? -1 : bp[ i ] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; }
jquery/sizzle
b2b650b629192beaf419098c459411a65121f5a1
Selector: Allow whitespace after hex escapes in CSS identifiers
diff --git a/dist/sizzle.js b/dist/sizzle.js index 5bd623a..f411ff8 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -1,677 +1,677 @@ /*! * Sizzle CSS Selector Engine v2.3.5-pre * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * - * Date: 2019-05-29 + * Date: 2019-07-02 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + - ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : - // Supplemental Plane codepoint (surrogate pair) + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = "#" + nid + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); diff --git a/dist/sizzle.min.js b/dist/sizzle.min.js index 981dc1e..db8e8bb 100644 --- a/dist/sizzle.min.js +++ b/dist/sizzle.min.js @@ -1,3 +1,3 @@ /*! Sizzle v2.3.5-pre | (c) JS Foundation and other contributors | js.foundation */ -!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),S=ae(),A=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); +!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),A=ae(),S=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){S(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!S[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){S(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=A[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=A(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); //# sourceMappingURL=sizzle.min.map \ No newline at end of file diff --git a/dist/sizzle.min.map b/dist/sizzle.min.map index 2003de8..be859bd 100644 --- a/dist/sizzle.min.map +++ b/dist/sizzle.min.map @@ -1 +1 @@ -{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","_argument","last","simple","forward","ofType","_context","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","_matchIndexes","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","_name","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACA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C,EAAKiD,SAASC,cAC5B,OAAOlD,EAAKqT,eAOTnN,GAAQ,SAAUC,GACvB,OAAwC,MAAjCA,EAAGnB,aAAc,eAExBsB,GAAWnG,EAAU,SAAUH,EAAMiK,EAAMtM,GAC1C,IAAIuM,EACJ,IAAMvM,EACL,OAAwB,IAAjBqC,EAAMiK,GAAkBA,EAAK/G,eACjCgH,EAAMlK,EAAKwI,iBAAkByB,KAAYC,EAAIE,UAC9CF,EAAIrE,MACJ,OAML,IAAIyN,GAAUhW,EAAOuG,OAErBA,GAAO0P,WAAa,WAKnB,OAJKjW,EAAOuG,SAAWA,KACtBvG,EAAOuG,OAASyP,IAGVzP,IAGe,mBAAX2P,QAAyBA,OAAOC,IAC3CD,OAAQ,WACP,OAAO3P,KAIqB,oBAAX6P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU9P,GAEjBvG,EAAOuG,OAASA,GA50EjB,CAi1EKvG","file":"sizzle.min.js"} \ No newline at end of file +{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","escape","nonHex","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","_argument","last","simple","forward","ofType","_context","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","_matchIndexes","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","_name","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GAIRsB,KAAgBC,eAChBC,KACAC,EAAMD,EAAIC,IACVC,EAAaF,EAAIG,KACjBA,EAAOH,EAAIG,KACXC,EAAQJ,EAAII,MAIZC,EAAU,SAAUC,EAAMC,GAGzB,IAFA,IAAIzC,EAAI,EACP0C,EAAMF,EAAKG,OACJ3C,EAAI0C,EAAK1C,IAChB,GAAKwC,EAAMxC,KAAQyC,EAClB,OAAOzC,EAGT,OAAQ,GAGT4C,EAAW,6HAMXC,EAAa,sBAGbC,EAAa,0BAA4BD,EACxC,0CAGDE,EAAa,MAAQF,EAAa,KAAOC,EAAa,OAASD,EAG9D,gBAAkBA,EAIlB,2DAA6DC,EAAa,OAC1ED,EAAa,OAEdG,EAAU,KAAOF,EAAa,wFAOAC,EAAa,eAO3CE,EAAc,IAAIC,OAAQL,EAAa,IAAK,KAC5CM,EAAQ,IAAID,OAAQ,IAAML,EAAa,8BACtCA,EAAa,KAAM,KAEpBO,EAAS,IAAIF,OAAQ,IAAML,EAAa,KAAOA,EAAa,KAC5DQ,EAAe,IAAIH,OAAQ,IAAML,EAAa,WAAaA,EAAa,IAAMA,EAC7E,KACDS,EAAW,IAAIJ,OAAQL,EAAa,MAEpCU,EAAU,IAAIL,OAAQF,GACtBQ,EAAc,IAAIN,OAAQ,IAAMJ,EAAa,KAE7CW,GACCC,GAAM,IAAIR,OAAQ,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EAAGyC,UAAY,WACfzC,EAAG6E,WAAW9F,aAAc,QAAS,IACY,KAA1CiB,EAAG6E,WAAWhG,aAAc,YAEnCsB,GAAW,QAAS,SAAUrG,EAAMkT,EAAOvV,GAC1C,IAAMA,GAAyC,UAAhCqC,EAAKgD,SAASC,cAC5B,OAAOjD,EAAKmT,eAOTlN,GAAQ,SAAUC,GACvB,OAAwC,MAAjCA,EAAGnB,aAAc,eAExBsB,GAAWlG,EAAU,SAAUH,EAAMgK,EAAMrM,GAC1C,IAAIsM,EACJ,IAAMtM,EACL,OAAwB,IAAjBqC,EAAMgK,GAAkBA,EAAK/G,eACjCgH,EAAMjK,EAAKuI,iBAAkByB,KAAYC,EAAIE,UAC9CF,EAAIrE,MACJ,OAML,IAAIwN,GAAU9V,EAAOsG,OAErBA,GAAOyP,WAAa,WAKnB,OAJK/V,EAAOsG,SAAWA,KACtBtG,EAAOsG,OAASwP,IAGVxP,IAGe,mBAAX0P,QAAyBA,OAAOC,IAC3CD,OAAQ,WACP,OAAO1P,KAIqB,oBAAX4P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU7P,GAEjBtG,EAAOsG,OAASA,GA50EjB,CAi1EKtG","file":"sizzle.min.js"} \ No newline at end of file diff --git a/src/sizzle.js b/src/sizzle.js index 2bb9065..7841b98 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -1,677 +1,677 @@ /*! * Sizzle CSS Selector Engine v@VERSION * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: @DATE */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + - ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : - // Supplemental Plane codepoint (surrogate pair) + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = "#" + nid + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); diff --git a/test/unit/selector.js b/test/unit/selector.js index 0e80f2f..729ea8c 100644 --- a/test/unit/selector.js +++ b/test/unit/selector.js @@ -1,1122 +1,1130 @@ QUnit.module( "selector", { beforeEach: setup } ); /* ======== testinit.js reference ======== See data/testinit.js q(...); Returns an array of elements with the given IDs @example q("main", "foo", "bar") => [<div id="main">, <span id="foo">, <input id="bar">] t( testName, selector, [ "array", "of", "ids" ] ); Asserts that a select matches the given IDs @example t("Check for something", "//[a]", ["foo", "baar"]); url( "some/url.php" ); Add random number to url to stop caching @example url("data/test.html") => "data/test.html?10538358428943" @example url("data/test.php?foo=bar") => "data/test.php?foo=bar&10538358345554" */ QUnit.test( "element", function( assert ) { assert.expect( 35 ); var form, all, good, i, lengthtest, siblingTest, html; assert.equal( Sizzle( "" ).length, 0, "Empty selector returns an empty array" ); assert.deepEqual( Sizzle( "div", document.createTextNode( "" ) ), [], "Text element as context fails silently" ); form = document.getElementById( "form" ); assert.ok( !Sizzle.matchesSelector( form, "" ), "Empty string passed to matchesSelector does not match" ); assert.equal( Sizzle( " " ).length, 0, "Empty selector returns an empty array" ); assert.equal( Sizzle( "\t" ).length, 0, "Empty selector returns an empty array" ); all = Sizzle( "*" ); assert.ok( all.length >= 30, "Select all" ); good = true; for ( i = 0; i < all.length; i++ ) { if ( all[ i ].nodeType === 8 ) { good = false; } } assert.ok( good, "Select all elements, no comment nodes" ); t( "Element Selector", "html", [ "html" ] ); t( "Element Selector", "body", [ "body" ] ); t( "Element Selector", "#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Leading space", " #qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Leading tab", "\t#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Leading carriage return", "\r#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Leading line feed", "\n#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Leading form feed", "\f#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Trailing space", "#qunit-fixture p ", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Trailing tab", "#qunit-fixture p\t", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Trailing carriage return", "#qunit-fixture p\r", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Trailing line feed", "#qunit-fixture p\n", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Trailing form feed", "#qunit-fixture p\f", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.deepEqual( jQuery( Sizzle( "div ol" ) ).filter( "#qunit-fixture *" ).get(), q( "empty", "listWithTabIndex" ), "Parent Element" ); assert.deepEqual( jQuery( Sizzle( "div\tol" ) ).filter( "#qunit-fixture *" ).get(), q( "empty", "listWithTabIndex" ), "Parent Element (non-space descendant combinator)" ); // Check for unique-ness and sort order assert.deepEqual( Sizzle( "p, div p" ), Sizzle( "p" ), "Check for duplicates: p, div p" ); jQuery( "<h1 id='h1'/><h2 id='h2'/><h2 id='h2-2'/>" ).prependTo( "#qunit-fixture" ); t( "Checking sort order", "#qunit-fixture h2, #qunit-fixture h1", [ "h1", "h2", "h2-2" ] ); t( "Checking sort order", "#qunit-fixture h2:first, #qunit-fixture h1:first", [ "h1", "h2" ] ); t( "Checking sort order", "#qunit-fixture p, #qunit-fixture p a", [ "firstp", "simon1", "ap", "google", "groups", "anchor1", "mark", "sndp", "en", "yahoo", "sap", "anchor2", "simon", "first" ] ); // Test Conflict ID lengthtest = document.getElementById( "lengthtest" ); assert.deepEqual( Sizzle( "#idTest", lengthtest ), q( "idTest" ), "Finding element with id of ID." ); assert.deepEqual( Sizzle( "[name='id']", lengthtest ), q( "idTest" ), "Finding element with id of ID." ); assert.deepEqual( Sizzle( "input[id='idTest']", lengthtest ), q( "idTest" ), "Finding elements with id of ID." ); siblingTest = document.getElementById( "siblingTest" ); assert.deepEqual( Sizzle( "div em", siblingTest ), [], "Element-rooted QSA does not select based on document context" ); assert.deepEqual( Sizzle( "div em, div em, div em:not(div em)", siblingTest ), [], "Element-rooted QSA does not select based on document context" ); assert.deepEqual( Sizzle( "div em, em\\,", siblingTest ), [], "Escaped commas do not get treated with an id in element-rooted QSA" ); html = ""; for ( i = 0; i < 100; i++ ) { html = "<div>" + html + "</div>"; } html = jQuery( html ).appendTo( document.body ); assert.ok( !!Sizzle( "body div div div" ).length, "No stack or performance problems with large amounts of descendants" ); assert.ok( !!Sizzle( "body>div div div" ).length, "No stack or performance problems with large amounts of descendants" ); html.remove(); // Real use case would be using .watch in browsers with window.watch (see Issue #157) q( "qunit-fixture" )[ 0 ].appendChild( document.createElement( "toString" ) ).id = "toString"; t( "Element name matches Object.prototype property", "toString#toString", [ "toString" ] ); } ); QUnit.test( "XML Document Selectors", function( assert ) { var xml = createWithFriesXML(); assert.expect( 11 ); assert.equal( Sizzle( "foo_bar", xml ).length, 1, "Element Selector with underscore" ); assert.equal( Sizzle( ".component", xml ).length, 1, "Class selector" ); assert.equal( Sizzle( "[class*=component]", xml ).length, 1, "Attribute selector for class" ); assert.equal( Sizzle( "property[name=prop2]", xml ).length, 1, "Attribute selector with name" ); assert.equal( Sizzle( "[name=prop2]", xml ).length, 1, "Attribute selector with name" ); assert.equal( Sizzle( "#seite1", xml ).length, 1, "Attribute selector with ID" ); assert.equal( Sizzle( "component#seite1", xml ).length, 1, "Attribute selector with ID" ); assert.equal( Sizzle.matches( "#seite1", Sizzle( "component", xml ) ).length, 1, "Attribute selector filter with ID" ); assert.equal( Sizzle( "meta property thing", xml ).length, 2, "Descendent selector and dir caching" ); assert.ok( Sizzle.matchesSelector( xml.lastChild, "soap\\:Envelope" ), "Check for namespaced element" ); xml = jQuery.parseXML( "<?xml version='1.0' encoding='UTF-8'?><root><elem id='1'/></root>" ); assert.equal( Sizzle( "elem:not(:has(*))", xml ).length, 1, "Non-qSA path correctly handles numeric ids (jQuery #14142)" ); } ); QUnit.test( "broken", function( assert ) { - assert.expect( 29 ); + assert.expect( 30 ); var attrbad, broken = function( name, selector ) { assert.throws( function() { // Setting context to null here somehow avoids QUnit's window.error handling // making the e & e.message correct // For whatever reason, without this, // Sizzle.error will be called but no error will be seen in oldIE Sizzle.call( null, selector ); }, function( e ) { return e.message.indexOf( "Syntax error" ) >= 0; }, name + ": " + selector ); }; broken( "Broken Selector", "[" ); broken( "Broken Selector", "(" ); broken( "Broken Selector", "{" ); broken( "Broken Selector", "<" ); broken( "Broken Selector", "()" ); broken( "Broken Selector", "<>" ); broken( "Broken Selector", "{}" ); broken( "Broken Selector", "," ); broken( "Broken Selector", ",a" ); broken( "Broken Selector", "a," ); + broken( "Identifier with bad escape", "foo\\\fbaz" ); // Hangs on IE 9 if regular expression is inefficient broken( "Broken Selector", "[id=012345678901234567890123456789" ); broken( "Doesn't exist", ":visble" ); broken( "Nth-child", ":nth-child" ); // Sigh again. IE 9 thinks this is also a real selector // not super critical that we fix this case //broken( "Nth-child", ":nth-child(-)" ); // Sigh. WebKit thinks this is a real selector in qSA // They've already fixed this and it'll be coming into // current browsers soon. Currently, Safari 5.0 still has this problem // broken( "Nth-child", ":nth-child(asdf)", [] ); broken( "Nth-child", ":nth-child(2n+-0)" ); broken( "Nth-child", ":nth-child(2+0)" ); broken( "Nth-child", ":nth-child(- 1n)" ); broken( "Nth-child", ":nth-child(-1 n)" ); broken( "First-child", ":first-child(n)" ); broken( "Last-child", ":last-child(n)" ); broken( "Only-child", ":only-child(n)" ); broken( "Nth-last-last-child", ":nth-last-last-child(1)" ); broken( "First-last-child", ":first-last-child" ); broken( "Last-last-child", ":last-last-child" ); broken( "Only-last-child", ":only-last-child" ); // Make sure attribute value quoting works correctly. See: #6093 attrbad = jQuery( "<input type='hidden' value='2' name='foo.baz' id='attrbad1'/><input type='hidden' value='2' name='foo[baz]' id='attrbad2'/>" ).appendTo( "#qunit-fixture" ); broken( "Attribute equals non-value", "input[name=]" ); - broken( "Attribute equals unquoted non-identifer", "input[name=foo.baz]" ); - broken( "Attribute equals unquoted non-identifer", "input[name=foo[baz]]" ); + broken( "Attribute equals unquoted non-identifier", "input[name=foo.baz]" ); + broken( "Attribute equals unquoted non-identifier", "input[name=foo[baz]]" ); broken( "Attribute equals bad string", "input[name=''double-quoted'']" ); broken( "Attribute equals bad string", "input[name='apostrophe'd']" ); } ); QUnit.test( "id", function( assert ) { assert.expect( 34 ); var fiddle, a; t( "ID Selector", "#body", [ "body" ] ); t( "ID Selector w/ Element", "body#body", [ "body" ] ); t( "ID Selector w/ Element", "ul#first", [] ); t( "ID selector with existing ID descendant", "#firstp #simon1", [ "simon1" ] ); t( "ID selector with non-existant descendant", "#firstp #foobar", [] ); t( "ID selector using UTF8", "#台北Táiběi", [ "台北Táiběi" ] ); t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", [ "台北Táiběi", "台北" ] ); t( "Descendant ID selector using UTF8", "div #台北", [ "台北" ] ); t( "Child ID selector using UTF8", "form > #台北", [ "台北" ] ); t( "Escaped ID", "#foo\\:bar", [ "foo:bar" ] ); t( "Escaped ID with descendant", "#foo\\:bar span:not(:input)", [ "foo_descendant" ] ); t( "Escaped ID", "#test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); t( "Descendant escaped ID", "div #foo\\:bar", [ "foo:bar" ] ); t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); t( "Child escaped ID", "form > #foo\\:bar", [ "foo:bar" ] ); t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); fiddle = jQuery( "<div id='fiddle\\Foo'><span id='fiddleSpan'></span></div>" ) .appendTo( "#qunit-fixture" ); assert.deepEqual( Sizzle( "> span", Sizzle( "#fiddle\\\\Foo" )[ 0 ] ), q( [ "fiddleSpan" ] ), "Escaped ID as context" ); fiddle.remove(); t( "ID Selector, child ID present", "#form > #radio1", [ "radio1" ] ); // bug #267 t( "ID Selector, not an ancestor ID", "#form #first", [] ); t( "ID Selector, not a child ID", "#form > #option1a", [] ); t( "All Children of ID", "#foo > *", [ "sndp", "en", "sap" ] ); t( "All Children of ID with no children", "#firstUL > *", [] ); assert.equal( Sizzle( "#tName1" )[ 0 ].id, "tName1", "ID selector with same value for a name attribute" ); t( "ID selector non-existing but name attribute on an A tag", "#tName2", [] ); t( "Leading ID selector non-existing but name attribute on an A tag", "#tName2 span", [] ); t( "Leading ID selector existing, retrieving the child", "#tName1 span", [ "tName1-span" ] ); assert.equal( Sizzle( "div > div #tName1" )[ 0 ].id, Sizzle( "#tName1-span" )[ 0 ].parentNode.id, "Ending with ID" ); a = jQuery( "<a id='backslash\\foo'></a>" ).appendTo( "#qunit-fixture" ); t( "ID Selector contains backslash", "#backslash\\\\foo", [ "backslash\\foo" ] ); t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", [ "lengthtest" ] ); t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986 assert.deepEqual( Sizzle( "div#form", document.body ), [], "ID selector within the context of another element" ); t( "Underscore ID", "#types_all", [ "types_all" ] ); t( "Dash ID", "#qunit-fixture", [ "qunit-fixture" ] ); t( "ID with weird characters in it", "#name\\+value", [ "name+value" ] ); } ); QUnit.test( "class", function( assert ) { assert.expect( 27 ); t( "Class Selector", ".blog", [ "mark", "simon" ] ); t( "Class Selector", ".GROUPS", [ "groups" ] ); t( "Class Selector", ".blog.link", [ "simon" ] ); t( "Class Selector w/ Element", "a.blog", [ "mark", "simon" ] ); t( "Parent Class Selector", "p .blog", [ "mark", "simon" ] ); t( "Class selector using UTF8", ".台北Táiběi", [ "utf8class1" ] ); //t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] ); t( "Class selector using UTF8", ".台北Táiběi.台北", [ "utf8class1" ] ); t( "Class selector using UTF8", ".台北Táiběi, .台北", [ "utf8class1", "utf8class2" ] ); t( "Descendant class selector using UTF8", "div .台北Táiběi", [ "utf8class1" ] ); t( "Child class selector using UTF8", "form > .台北Táiběi", [ "utf8class1" ] ); t( "Escaped Class", ".foo\\:bar", [ "foo:bar" ] ); t( "Escaped Class", ".test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); t( "Descendant escaped Class", "div .foo\\:bar", [ "foo:bar" ] ); t( "Descendant escaped Class", "div .test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); t( "Child escaped Class", "form > .foo\\:bar", [ "foo:bar" ] ); t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); var div = document.createElement( "div" ); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; assert.deepEqual( Sizzle( ".e", div ), [ div.firstChild ], "Finding a second class." ); div.lastChild.className = "e"; assert.deepEqual( Sizzle( ".e", div ), [ div.firstChild, div.lastChild ], "Finding a modified class." ); assert.ok( !Sizzle.matchesSelector( div, ".null" ), ".null does not match an element with no class" ); assert.ok( !Sizzle.matchesSelector( div.firstChild, ".null div" ), ".null does not match an element with no class" ); div.className = "null"; assert.ok( Sizzle.matchesSelector( div, ".null" ), ".null matches element with class 'null'" ); assert.ok( Sizzle.matchesSelector( div.firstChild, ".null div" ), "caching system respects DOM changes" ); assert.ok( !Sizzle.matchesSelector( document, ".foo" ), "testing class on document doesn't error" ); assert.ok( !Sizzle.matchesSelector( window, ".foo" ), "testing class on window doesn't error" ); div.lastChild.className += " hasOwnProperty toString"; assert.deepEqual( Sizzle( ".e.hasOwnProperty.toString", div ), [ div.lastChild ], "Classes match Object.prototype properties" ); div = jQuery( "<div><svg width='200' height='250' version='1.1'" + " xmlns='http://www.w3.org/2000/svg'><rect x='10' y='10' width='30' height='30'" + "class='foo'></rect></svg></div>" )[ 0 ]; assert.equal( Sizzle( ".foo", div ).length, 1, "Class selector against SVG container" ); // Support: IE <=7 // Test SVG selection only if SVG works if ( div.firstChild.firstChild ) { assert.equal( Sizzle( ".foo", div.firstChild ).length, 1, "Class selector directly against SVG" ); } else { assert.ok( true, "SVG not supported" ); } } ); QUnit.test( "name", function( assert ) { assert.expect( 14 ); var form; t( "Name selector", "input[name=action]", [ "text1" ] ); t( "Name selector with single quotes", "input[name='action']", [ "text1" ] ); t( "Name selector with double quotes", "input[name=\"action\"]", [ "text1" ] ); t( "Name selector non-input", "[name=example]", [ "name-is-example" ] ); t( "Name selector non-input", "[name=div]", [ "name-is-div" ] ); t( "Name selector non-input", "*[name=iframe]", [ "iframe" ] ); t( "Name selector for grouped input", "input[name='types[]']", [ "types_all", "types_anime", "types_movie" ] ); form = document.getElementById( "form" ); assert.deepEqual( Sizzle( "input[name=action]", form ), q( "text1" ), "Name selector within the context of another element" ); assert.deepEqual( Sizzle( "input[name='foo[bar]']", form ), q( "hidden2" ), "Name selector for grouped form element within the context of another element" ); form = jQuery( "<form><input name='id'/></form>" ).appendTo( "body" ); assert.equal( Sizzle( "input", form[ 0 ] ).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); form.remove(); t( "Find elements that have similar IDs", "[name=tName1]", [ "tName1ID" ] ); t( "Find elements that have similar IDs", "[name=tName2]", [ "tName2ID" ] ); t( "Find elements that have similar IDs", "#tName2ID", [ "tName2ID" ] ); t( "Case-sensitivity", "[name=tname1]", [] ); } ); QUnit.test( "multiple", function( assert ) { assert.expect( 6 ); jQuery( "#qunit-fixture" ).prepend( "<h2 id='h2'/>" ); t( "Comma Support", "#qunit-fixture h2, #qunit-fixture p", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Comma Support", "#qunit-fixture h2 , #qunit-fixture p", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Comma Support", "#qunit-fixture h2 , #qunit-fixture p", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Comma Support", "#qunit-fixture h2,#qunit-fixture p", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Comma Support", "#qunit-fixture h2,#qunit-fixture p ", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Comma Support", "#qunit-fixture h2\t,\r#qunit-fixture p\n", [ "h2", "firstp", "ap", "sndp", "en", "sap", "first" ] ); } ); QUnit.test( "child and adjacent", function( assert ) { assert.expect( 43 ); var siblingFirst, en, nothiddendiv; t( "Child", "p > a", [ "simon1", "google", "groups", "mark", "yahoo", "simon" ] ); t( "Child minus whitespace", "p>a", [ "simon1", "google", "groups", "mark", "yahoo", "simon" ] ); t( "Child minus trailing whitespace", "p> a", [ "simon1", "google", "groups", "mark", "yahoo", "simon" ] ); t( "Child minus leading whitespace", "p >a", [ "simon1", "google", "groups", "mark", "yahoo", "simon" ] ); t( "Child w/ Class", "p > a.blog", [ "mark", "simon" ] ); t( "All Children", "code > *", [ "anchor1", "anchor2" ] ); t( "All Grandchildren", "p > * > *", [ "anchor1", "anchor2" ] ); t( "Rooted tag adjacent", "#qunit-fixture a + a", [ "groups", "tName2ID" ] ); t( "Rooted tag adjacent minus whitespace", "#qunit-fixture a+a", [ "groups", "tName2ID" ] ); t( "Rooted tag adjacent minus leading whitespace", "#qunit-fixture a +a", [ "groups", "tName2ID" ] ); t( "Rooted tag adjacent minus trailing whitespace", "#qunit-fixture a+ a", [ "groups", "tName2ID" ] ); t( "Tag adjacent", "p + p", [ "ap", "en", "sap" ] ); t( "#id adjacent", "#firstp + p", [ "ap" ] ); t( "Tag#id adjacent", "p#firstp + p", [ "ap" ] ); t( "Tag[attr] adjacent", "p[lang=en] + p", [ "sap" ] ); t( "Tag.class adjacent", "a.GROUPS + code + a", [ "mark" ] ); t( "Comma, Child, and Adjacent", "#qunit-fixture a + a, code > a", [ "groups", "anchor1", "anchor2", "tName2ID" ] ); t( "Element Preceded By", "#qunit-fixture p ~ div", [ "foo", "nothiddendiv", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest" ] ); t( "Element Preceded By", "#first ~ div", [ "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest" ] ); t( "Element Preceded By", "#groups ~ a", [ "mark" ] ); t( "Element Preceded By", "#length ~ input", [ "idTest" ] ); t( "Element Preceded By", "#siblingfirst ~ em", [ "siblingnext", "siblingthird" ] ); t( "Element Preceded By (multiple)", "#siblingTest em ~ em ~ em ~ span", [ "siblingspan" ] ); t( "Element Preceded By, Containing", "#liveHandlerOrder ~ div em:contains('1')", [ "siblingfirst" ] ); siblingFirst = document.getElementById( "siblingfirst" ); assert.deepEqual( Sizzle( "~ em", siblingFirst ), q( "siblingnext", "siblingthird" ), "Element Preceded By with a context." ); assert.deepEqual( Sizzle( "+ em", siblingFirst ), q( "siblingnext" ), "Element Directly Preceded By with a context." ); assert.deepEqual( Sizzle( "~ em:first", siblingFirst ), q( "siblingnext" ), "Element Preceded By positional with a context." ); en = document.getElementById( "en" ); assert.deepEqual( Sizzle( "+ p, a", en ), q( "yahoo", "sap" ), "Compound selector with context, beginning with sibling test." ); assert.deepEqual( Sizzle( "a, + p", en ), q( "yahoo", "sap" ), "Compound selector with context, containing sibling test." ); t( "Multiple combinators selects all levels", "#siblingTest em *", [ "siblingchild", "siblinggrandchild", "siblinggreatgrandchild" ] ); t( "Multiple combinators selects all levels", "#siblingTest > em *", [ "siblingchild", "siblinggrandchild", "siblinggreatgrandchild" ] ); t( "Multiple sibling combinators doesn't miss general siblings", "#siblingTest > em:first-child + em ~ span", [ "siblingspan" ] ); t( "Combinators are not skipped when mixing general and specific", "#siblingTest > em:contains('x') + em ~ span", [] ); assert.equal( Sizzle( "#listWithTabIndex" ).length, 1, "Parent div for next test is found via ID (#8310)" ); assert.equal( Sizzle( "#listWithTabIndex li:eq(2) ~ li" ).length, 1, "Find by general sibling combinator (#8310)" ); assert.equal( Sizzle( "#__sizzle__" ).length, 0, "Make sure the temporary id assigned by sizzle is cleared out (#8310)" ); assert.equal( Sizzle( "#listWithTabIndex" ).length, 1, "Parent div for previous test is still found via ID (#8310)" ); t( "Verify deep class selector", "div.blah > p > a", [] ); t( "No element deep selector", "div.foo > span > a", [] ); nothiddendiv = document.getElementById( "nothiddendiv" ); assert.deepEqual( Sizzle( "> :first", nothiddendiv ), q( "nothiddendivchild" ), "Verify child context positional selector" ); assert.deepEqual( Sizzle( "> :eq(0)", nothiddendiv ), q( "nothiddendivchild" ), "Verify child context positional selector" ); assert.deepEqual( Sizzle( "> *:first", nothiddendiv ), q( "nothiddendivchild" ), "Verify child context positional selector" ); t( "Non-existant ancestors", ".fototab > .thumbnails > a", [] ); } ); QUnit.test( "attributes - existence", function( assert ) { assert.expect( 7 ); t( "on element", "#qunit-fixture a[title]", [ "google" ] ); t( "on element (whitespace ignored)", "#qunit-fixture a[ title ]", [ "google" ] ); t( "on element (case-insensitive)", "#qunit-fixture a[TITLE]", [ "google" ] ); t( "on any element", "#qunit-fixture *[title]", [ "google" ] ); t( "on implicit element", "#qunit-fixture [title]", [ "google" ] ); t( "boolean", "#select2 option[selected]", [ "option2d" ] ); t( "for attribute on label", "form label[for]", [ "label-for" ] ); } ); QUnit.test( "attributes - equals", function( assert ) { assert.expect( 20 ); t( "identifier", "#qunit-fixture a[rel=bookmark]", [ "simon1" ] ); t( "identifier containing underscore", "input[id=types_all]", [ "types_all" ] ); t( "string", "#qunit-fixture a[rel='bookmark']", [ "simon1" ] ); t( "string (whitespace ignored)", "#qunit-fixture a[ rel = 'bookmark' ]", [ "simon1" ] ); t( "non-identifier string", "#qunit-fixture a[href='http://www.google.com/']", [ "google" ] ); t( "empty string", "#select1 option[value='']", [ "option1a" ] ); t( "number", "#qunit-fixture option[value=1]", [ "option1b", "option2b", "option3b", "option4b", "option5c" ] ); t( "negative number", "#qunit-fixture li[tabIndex=-1]", [ "foodWithNegativeTabIndex" ] ); t( "non-ASCII identifier", "span[lang=中文]", [ "台北" ] ); t( "input[type=text]", "#form input[type=text]", [ "text1", "text2", "hidden2", "name" ] ); t( "input[type=search]", "#form input[type=search]", [ "search" ] ); t( "script[src] (jQuery #13777)", "#moretests script[src]", [ "script-src" ] ); t( "boolean attribute equals name", "#select2 option[selected='selected']", [ "option2d" ] ); t( "for attribute in form", "#form [for=action]", [ "label-for" ] ); t( "name attribute", "input[name='foo[bar]']", [ "hidden2" ] ); t( "value attribute", "input[value=Test]", [ "text1", "text2" ] ); assert.deepEqual( Sizzle( "input[data-comma='0,1']" ), q( "el12087" ), "Without context, single-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma=\"0,1\"]" ), q( "el12087" ), "Without context, double-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma='0,1']", document.getElementById( "t12087" ) ), q( "el12087" ), "With context, single-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma=\"0,1\"]", document.getElementById( "t12087" ) ), q( "el12087" ), "With context, double-quoted attribute containing ','" ); } ); QUnit.test( "attributes - does not equal", function( assert ) { assert.expect( 2 ); t( "string", "#ap a[hreflang!='en']", [ "google", "groups", "anchor1" ] ); t( "empty string", "#select1 option[value!='']", [ "option1b", "option1c", "option1d" ] ); } ); QUnit.test( "attributes - starts with", function( assert ) { assert.expect( 4 ); // Support: IE<8 // There is apparently no way to bypass interpolation of the *originally-defined* href attribute document.getElementById( "anchor2" ).href = "#2"; t( "string (whitespace ignored)", "a[href ^= 'http://www']", [ "google", "yahoo" ] ); t( "href starts with hash", "p a[href^='#']", [ "anchor2" ] ); t( "string containing '['", "input[name^='foo[']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name^='foo[bar]']", [ "hidden2" ] ); } ); QUnit.test( "attributes - contains", function( assert ) { assert.expect( 4 ); t( "string (whitespace ignored)", "a[href *= 'google']", [ "google", "groups" ] ); t( "string starting with '[' ... ']'", "input[name*='[bar]']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name*='foo[bar]']", [ "hidden2" ] ); t( "href contains hash", "p a[href*='#']", [ "simon1", "anchor2" ] ); } ); QUnit.test( "attributes - ends with", function( assert ) { assert.expect( 4 ); t( "string (whitespace ignored)", "a[href $= 'org/']", [ "mark" ] ); t( "string ending with ']'", "input[name$='bar]']", [ "hidden2" ] ); t( "string like '[' ... ']'", "input[name$='[bar]']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name$='foo[bar]']", [ "hidden2" ] ); } ); QUnit.test( "attributes - whitespace list includes", function( assert ) { assert.expect( 3 ); t( "string found at the beginning", "input[data-15233~='foo']", [ "t15233-single", "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); t( "string found in the middle", "input[data-15233~='bar']", [ "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); t( "string found at the end", "input[data-15233~='baz']", [ "t15233-triple" ] ); } ); QUnit.test( "attributes - hyphen-prefix matches", function( assert ) { assert.expect( 3 ); t( "string", "#names-group span[id|='name']", [ "name-is-example", "name-is-div" ] ); t( "string containing hyphen", "#names-group span[id|='name-is']", [ "name-is-example", "name-is-div" ] ); t( "string ending with hyphen", "#names-group span[id|='name-is-']", [] ); } ); QUnit.test( "attributes - special characters", function( assert ) { - assert.expect( 13 ); + assert.expect( 15 ); var attrbad, div = document.createElement( "div" ); // #3279 div.innerHTML = "<div id='foo' xml:test='something'></div>"; assert.deepEqual( Sizzle( "[xml\\:test]", div ), [ div.firstChild ], "attribute name containing colon" ); // Make sure attribute value quoting works correctly. See jQuery #6093; #6428; #13894 // Use seeded results to bypass querySelectorAll optimizations attrbad = jQuery( "<input type='hidden' id='attrbad_space' name='foo bar'/>" + "<input type='hidden' id='attrbad_dot' value='2' name='foo.baz'/>" + "<input type='hidden' id='attrbad_brackets' value='2' name='foo[baz]'/>" + + "<input type='hidden' id='attrbad_leading_digits' name='agent' value='007'/>" + "<input type='hidden' id='attrbad_injection' data-attr='foo_baz&#39;]'/>" + "<input type='hidden' id='attrbad_quote' data-attr='&#39;'/>" + "<input type='hidden' id='attrbad_backslash' data-attr='&#92;'/>" + "<input type='hidden' id='attrbad_backslash_quote' data-attr='&#92;&#39;'/>" + "<input type='hidden' id='attrbad_backslash_backslash' data-attr='&#92;&#92;'/>" + "<input type='hidden' id='attrbad_unicode' data-attr='&#x4e00;'/>" ).appendTo( "#qunit-fixture" ).get(); assert.deepEqual( Sizzle( "input[name=foo\\ bar]", null, null, attrbad ), q( "attrbad_space" ), "identifier containing space" ); assert.deepEqual( Sizzle( "input[name=foo\\.baz]", null, null, attrbad ), q( "attrbad_dot" ), "identifier containing dot" ); assert.deepEqual( Sizzle( "input[name=foo\\[baz\\]]", null, null, attrbad ), q( "attrbad_brackets" ), "identifier containing brackets" ); assert.deepEqual( Sizzle( "input[data-attr='foo_baz\\']']", null, null, attrbad ), q( "attrbad_injection" ), "string containing quote and right bracket" ); + assert.deepEqual( Sizzle( "input[value=\\30 \\30\\37 ]", null, null, attrbad ), + q( "attrbad_leading_digits" ), + "identifier containing escaped leading digits with whitespace termination" ); + assert.deepEqual( Sizzle( "input[value=\\00003007]", null, null, attrbad ), + q( "attrbad_leading_digits" ), + "identifier containing escaped leading digits without whitespace termination" ); assert.deepEqual( Sizzle( "input[data-attr='\\'']", null, null, attrbad ), q( "attrbad_quote" ), "string containing quote" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\']", null, null, attrbad ), q( "attrbad_backslash" ), "string containing backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\\\'']", null, null, attrbad ), q( "attrbad_backslash_quote" ), "string containing backslash and quote" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing adjacent backslashes" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C \\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape-with-trailing-space backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C\t\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape-with-trailing-tab backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\04e00']", null, null, attrbad ), q( "attrbad_unicode" ), "Long numeric escape (BMP)" ); document.getElementById( "attrbad_unicode" ).setAttribute( "data-attr", "\uD834\uDF06A" ); // It was too much code to fix Safari 5.x Supplemental Plane crashes (see ba5f09fa404379a87370ec905ffa47f8ac40aaa3) // assert.deepEqual( Sizzle( "input[data-attr='\\01D306A']", null, null, attrbad ), // q( "attrbad_unicode" ), // "Long numeric escape (non-BMP)" ); } ); QUnit.test( "attributes - other", function( assert ) { assert.expect( 7 ); var div = document.getElementById( "foo" ); t( "Selector list with multiple quoted attribute-equals", "#form input[type='radio'], #form input[type='hidden']", [ "radio1", "radio2", "hidden1" ] ); t( "Selector list with differently-quoted attribute-equals", "#form input[type='radio'], #form input[type=\"hidden\"]", [ "radio1", "radio2", "hidden1" ] ); t( "Selector list with quoted and unquoted attribute-equals", "#form input[type='radio'], #form input[type=hidden]", [ "radio1", "radio2", "hidden1" ] ); t( "attribute name is Object.prototype property \"constructor\" (negative)", "[constructor]", [] ); t( "attribute name is Gecko Object.prototype property \"watch\" (negative)", "[watch]", [] ); div.setAttribute( "constructor", "foo" ); div.setAttribute( "watch", "bar" ); t( "attribute name is Object.prototype property \"constructor\"", "[constructor='foo']", [ "foo" ] ); t( "attribute name is Gecko Object.prototype property \"watch\"", "[watch='bar']", [ "foo" ] ); } ); QUnit.test( "pseudo - (parent|empty)", function( assert ) { assert.expect( 3 ); t( "Empty", "#qunit-fixture ul:empty", [ "firstUL" ] ); t( "Empty with comment node", "#qunit-fixture ol:empty", [ "empty" ] ); t( "Is A Parent", "#qunit-fixture p:parent", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); } ); QUnit.test( "pseudo - (first|last|only)-(child|of-type)", function( assert ) { assert.expect( 12 ); t( "First Child", "#qunit-fixture p:first-child", [ "firstp", "sndp" ] ); t( "First Child (leading id)", "#qunit-fixture p:first-child", [ "firstp", "sndp" ] ); t( "First Child (leading class)", ".nothiddendiv div:first-child", [ "nothiddendivchild" ] ); t( "First Child (case-insensitive)", "#qunit-fixture p:FIRST-CHILD", [ "firstp", "sndp" ] ); t( "Last Child", "#qunit-fixture p:last-child", [ "sap" ] ); t( "Last Child (leading id)", "#qunit-fixture a:last-child", [ "simon1", "anchor1", "mark", "yahoo", "anchor2", "simon", "liveLink1", "liveLink2" ] ); t( "Only Child", "#qunit-fixture a:only-child", [ "simon1", "anchor1", "yahoo", "anchor2", "liveLink1", "liveLink2" ] ); t( "First-of-type", "#qunit-fixture > p:first-of-type", [ "firstp" ] ); t( "Last-of-type", "#qunit-fixture > p:last-of-type", [ "first" ] ); t( "Only-of-type", "#qunit-fixture > :only-of-type", [ "name+value", "firstUL", "empty", "floatTest", "iframe", "table", "last" ] ); // Verify that the child position isn't being cached improperly var secondChildren = jQuery( "p:nth-child(2)" ).before( "<div></div>" ); t( "No longer second child", "p:nth-child(2)", [] ); secondChildren.prev().remove(); t( "Restored second child", "p:nth-child(2)", [ "ap", "en" ] ); } ); QUnit.test( "pseudo - nth-child", function( assert ) { assert.expect( 30 ); t( "Nth-child", "p:nth-child(1)", [ "firstp", "sndp" ] ); t( "Nth-child (with whitespace)", "p:nth-child( 1 )", [ "firstp", "sndp" ] ); t( "Nth-child (case-insensitive)", "#form select:first option:NTH-child(3)", [ "option1c" ] ); t( "Not nth-child", "#qunit-fixture p:not(:nth-child(1))", [ "ap", "en", "sap", "first" ] ); t( "Nth-child(2)", "#qunit-fixture form#form > *:nth-child(2)", [ "text1" ] ); t( "Nth-child(2)", "#qunit-fixture form#form > :nth-child(2)", [ "text1" ] ); t( "Nth-child(-1)", "#form select:first option:nth-child(-1)", [] ); t( "Nth-child(3)", "#form select:first option:nth-child(3)", [ "option1c" ] ); t( "Nth-child(0n+3)", "#form select:first option:nth-child(0n+3)", [ "option1c" ] ); t( "Nth-child(1n+0)", "#form select:first option:nth-child(1n+0)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-child(1n)", "#form select:first option:nth-child(1n)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-child(n)", "#form select:first option:nth-child(n)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-child(even)", "#form select:first option:nth-child(even)", [ "option1b", "option1d" ] ); t( "Nth-child(odd)", "#form select:first option:nth-child(odd)", [ "option1a", "option1c" ] ); t( "Nth-child(2n)", "#form select:first option:nth-child(2n)", [ "option1b", "option1d" ] ); t( "Nth-child(2n+1)", "#form select:first option:nth-child(2n+1)", [ "option1a", "option1c" ] ); t( "Nth-child(2n + 1)", "#form select:first option:nth-child(2n + 1)", [ "option1a", "option1c" ] ); t( "Nth-child(+2n + 1)", "#form select:first option:nth-child(+2n + 1)", [ "option1a", "option1c" ] ); t( "Nth-child(3n)", "#form select:first option:nth-child(3n)", [ "option1c" ] ); t( "Nth-child(3n+1)", "#form select:first option:nth-child(3n+1)", [ "option1a", "option1d" ] ); t( "Nth-child(3n+2)", "#form select:first option:nth-child(3n+2)", [ "option1b" ] ); t( "Nth-child(3n+3)", "#form select:first option:nth-child(3n+3)", [ "option1c" ] ); t( "Nth-child(3n-1)", "#form select:first option:nth-child(3n-1)", [ "option1b" ] ); t( "Nth-child(3n-2)", "#form select:first option:nth-child(3n-2)", [ "option1a", "option1d" ] ); t( "Nth-child(3n-3)", "#form select:first option:nth-child(3n-3)", [ "option1c" ] ); t( "Nth-child(3n+0)", "#form select:first option:nth-child(3n+0)", [ "option1c" ] ); t( "Nth-child(-1n+3)", "#form select:first option:nth-child(-1n+3)", [ "option1a", "option1b", "option1c" ] ); t( "Nth-child(-n+3)", "#form select:first option:nth-child(-n+3)", [ "option1a", "option1b", "option1c" ] ); t( "Nth-child(-1n + 3)", "#form select:first option:nth-child(-1n + 3)", [ "option1a", "option1b", "option1c" ] ); assert.deepEqual( Sizzle( ":nth-child(n)", null, null, [ document.createElement( "a" ) ].concat( q( "ap" ) ) ), q( "ap" ), "Seeded nth-child" ); } ); QUnit.test( "pseudo - nth-last-child", function( assert ) { assert.expect( 30 ); jQuery( "#qunit-fixture" ).append( "<form id='nth-last-child-form'/><i/><i/><i/><i/>" ); t( "Nth-last-child", "form:nth-last-child(5)", [ "nth-last-child-form" ] ); t( "Nth-last-child (with whitespace)", "form:nth-last-child( 5 )", [ "nth-last-child-form" ] ); t( "Nth-last-child (case-insensitive)", "#form select:first option:NTH-last-child(3)", [ "option1b" ] ); t( "Not nth-last-child", "#qunit-fixture p:not(:nth-last-child(1))", [ "firstp", "ap", "sndp", "en", "first" ] ); t( "Nth-last-child(-1)", "#form select:first option:nth-last-child(-1)", [] ); t( "Nth-last-child(3)", "#form select:first :nth-last-child(3)", [ "option1b" ] ); t( "Nth-last-child(3)", "#form select:first *:nth-last-child(3)", [ "option1b" ] ); t( "Nth-last-child(3)", "#form select:first option:nth-last-child(3)", [ "option1b" ] ); t( "Nth-last-child(0n+3)", "#form select:first option:nth-last-child(0n+3)", [ "option1b" ] ); t( "Nth-last-child(1n+0)", "#form select:first option:nth-last-child(1n+0)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-last-child(1n)", "#form select:first option:nth-last-child(1n)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-last-child(n)", "#form select:first option:nth-last-child(n)", [ "option1a", "option1b", "option1c", "option1d" ] ); t( "Nth-last-child(even)", "#form select:first option:nth-last-child(even)", [ "option1a", "option1c" ] ); t( "Nth-last-child(odd)", "#form select:first option:nth-last-child(odd)", [ "option1b", "option1d" ] ); t( "Nth-last-child(2n)", "#form select:first option:nth-last-child(2n)", [ "option1a", "option1c" ] ); t( "Nth-last-child(2n+1)", "#form select:first option:nth-last-child(2n+1)", [ "option1b", "option1d" ] ); t( "Nth-last-child(2n + 1)", "#form select:first option:nth-last-child(2n + 1)", [ "option1b", "option1d" ] ); t( "Nth-last-child(+2n + 1)", "#form select:first option:nth-last-child(+2n + 1)", [ "option1b", "option1d" ] ); t( "Nth-last-child(3n)", "#form select:first option:nth-last-child(3n)", [ "option1b" ] ); t( "Nth-last-child(3n+1)", "#form select:first option:nth-last-child(3n+1)", [ "option1a", "option1d" ] ); t( "Nth-last-child(3n+2)", "#form select:first option:nth-last-child(3n+2)", [ "option1c" ] ); t( "Nth-last-child(3n+3)", "#form select:first option:nth-last-child(3n+3)", [ "option1b" ] ); t( "Nth-last-child(3n-1)", "#form select:first option:nth-last-child(3n-1)", [ "option1c" ] ); t( "Nth-last-child(3n-2)", "#form select:first option:nth-last-child(3n-2)", [ "option1a", "option1d" ] ); t( "Nth-last-child(3n-3)", "#form select:first option:nth-last-child(3n-3)", [ "option1b" ] ); t( "Nth-last-child(3n+0)", "#form select:first option:nth-last-child(3n+0)", [ "option1b" ] ); t( "Nth-last-child(-1n+3)", "#form select:first option:nth-last-child(-1n+3)", [ "option1b", "option1c", "option1d" ] ); t( "Nth-last-child(-n+3)", "#form select:first option:nth-last-child(-n+3)", [ "option1b", "option1c", "option1d" ] ); t( "Nth-last-child(-1n + 3)", "#form select:first option:nth-last-child(-1n + 3)", [ "option1b", "option1c", "option1d" ] ); QUnit.deepEqual( Sizzle( ":nth-last-child(n)", null, null, [ document.createElement( "a" ) ].concat( q( "ap" ) ) ), q( "ap" ), "Seeded nth-last-child" ); } ); QUnit.test( "pseudo - nth-of-type", function( assert ) { assert.expect( 9 ); t( "Nth-of-type(-1)", ":nth-of-type(-1)", [] ); t( "Nth-of-type(3)", "#ap :nth-of-type(3)", [ "mark" ] ); t( "Nth-of-type(n)", "#ap :nth-of-type(n)", [ "google", "groups", "code1", "anchor1", "mark" ] ); t( "Nth-of-type(0n+3)", "#ap :nth-of-type(0n+3)", [ "mark" ] ); t( "Nth-of-type(2n)", "#ap :nth-of-type(2n)", [ "groups" ] ); t( "Nth-of-type(even)", "#ap :nth-of-type(even)", [ "groups" ] ); t( "Nth-of-type(2n+1)", "#ap :nth-of-type(2n+1)", [ "google", "code1", "anchor1", "mark" ] ); t( "Nth-of-type(odd)", "#ap :nth-of-type(odd)", [ "google", "code1", "anchor1", "mark" ] ); t( "Nth-of-type(-n+2)", "#qunit-fixture > :nth-of-type(-n+2)", [ "firstp", "ap", "foo", "nothiddendiv", "name+value", "firstUL", "empty", "form", "floatTest", "iframe", "lengthtest", "table", "last" ] ); } ); QUnit.test( "pseudo - nth-last-of-type", function( assert ) { assert.expect( 9 ); t( "Nth-last-of-type(-1)", ":nth-last-of-type(-1)", [] ); t( "Nth-last-of-type(3)", "#ap :nth-last-of-type(3)", [ "google" ] ); t( "Nth-last-of-type(n)", "#ap :nth-last-of-type(n)", [ "google", "groups", "code1", "anchor1", "mark" ] ); t( "Nth-last-of-type(0n+3)", "#ap :nth-last-of-type(0n+3)", [ "google" ] ); t( "Nth-last-of-type(2n)", "#ap :nth-last-of-type(2n)", [ "groups" ] ); t( "Nth-last-of-type(even)", "#ap :nth-last-of-type(even)", [ "groups" ] ); t( "Nth-last-of-type(2n+1)", "#ap :nth-last-of-type(2n+1)", [ "google", "code1", "anchor1", "mark" ] ); t( "Nth-last-of-type(odd)", "#ap :nth-last-of-type(odd)", [ "google", "code1", "anchor1", "mark" ] ); t( "Nth-last-of-type(-n+2)", "#qunit-fixture > :nth-last-of-type(-n+2)", [ "ap", "name+value", "first", "firstUL", "empty", "floatTest", "iframe", "table", "testForm", "liveHandlerOrder", "disabled-tests", "siblingTest", "last" ] ); } ); QUnit.test( "pseudo - has", function( assert ) { assert.expect( 3 ); t( "Basic test", "p:has(a)", [ "firstp", "ap", "en", "sap" ] ); t( "Basic test (irrelevant whitespace)", "p:has( a )", [ "firstp", "ap", "en", "sap" ] ); t( "Nested with overlapping candidates", "#qunit-fixture div:has(div:has(div:not([id])))", [ "moretests", "t2037" ] ); } ); QUnit.test( "pseudo - contains", function( assert ) { assert.expect( 9 ); var gh335 = document.getElementById( "qunit-fixture" ).appendChild( document.createElement( "mark" ) ); gh335.id = "gh-335"; gh335.appendChild( document.createTextNode( "raw line 1\nline 2" ) ); assert.ok( Sizzle( "a:contains('')" ).length, "empty string" ); t( "unquoted argument", "a:contains(Google)", [ "google", "groups" ] ); t( "unquoted argument with whitespace", "a:contains(Google Groups)", [ "groups" ] ); t( "quoted argument with whitespace and parentheses", "a:contains('Google Groups (Link)')", [ "groups" ] ); t( "quoted argument with double quotes and parentheses", "a:contains(\"(Link)\")", [ "groups" ] ); t( "unquoted argument with whitespace and paired parentheses", "a:contains(Google Groups (Link))", [ "groups" ] ); t( "unquoted argument with paired parentheses", "a:contains((Link))", [ "groups" ] ); t( "quoted argument with CSS escapes", "span:contains(\"\\\"'\\53F0 \\5317 Ta\\301 ibe\\30C i\")", [ "utf8class1" ] ); t( "collapsed whitespace", "mark:contains('line 1\\A line')", [ "gh-335" ] ); } ); QUnit.test( "pseudo - misc", function( assert ) { assert.expect( 32 ); var select, tmp, input; jQuery( "<h1 id='h1'/><h2 id='h2'/><h2 id='h2-2'/>" ).prependTo( "#qunit-fixture" ); t( "Headers", "#qunit-fixture :header", [ "h1", "h2", "h2-2" ] ); t( "Headers(case-insensitive)", "#qunit-fixture :Header", [ "h1", "h2", "h2-2" ] ); t( "Multiple matches with the same context (cache check)", "#form select:has(option:first-child:contains('o'))", [ "select1", "select2", "select3", "select4" ] ); assert.ok( Sizzle( "#qunit-fixture :not(:has(:has(*)))" ).length, "All not grandparents" ); select = document.getElementById( "select1" ); assert.ok( Sizzle.matchesSelector( select, ":has(option)" ), "Has Option Matches" ); tmp = document.createElement( "div" ); tmp.id = "tmp_input"; document.body.appendChild( tmp ); jQuery.each( [ "button", "submit", "reset" ], function( i, type ) { var els = jQuery( "<input id='input_%' type='%'/><button id='button_%' type='%'>test</button>" .replace( /%/g, type ) ).appendTo( tmp ); t( "Input Buttons :" + type, "#tmp_input :" + type, [ "input_" + type, "button_" + type ] ); assert.ok( Sizzle.matchesSelector( els[ 0 ], ":" + type ), "Input Matches :" + type ); assert.ok( Sizzle.matchesSelector( els[ 1 ], ":" + type ), "Button Matches :" + type ); } ); document.body.removeChild( tmp ); // Recreate tmp tmp = document.createElement( "div" ); tmp.id = "tmp_input"; tmp.innerHTML = "<span>Hello I am focusable.</span>"; // Setting tabIndex should make the element focusable // http://dev.w3.org/html5/spec/single-page.html#focus-management document.body.appendChild( tmp ); tmp.tabIndex = 0; tmp.focus(); if ( document.activeElement !== tmp || ( document.hasFocus && !document.hasFocus() ) || ( document.querySelectorAll && !document.querySelectorAll( "div:focus" ).length ) ) { assert.ok( true, "The div was not focused. Skip checking the :focus match." ); assert.ok( true, "The div was not focused. Skip checking the :focus match." ); } else { t( "tabIndex element focused", ":focus", [ "tmp_input" ] ); assert.ok( Sizzle.matchesSelector( tmp, ":focus" ), ":focus matches tabIndex div" ); } // Blur tmp tmp.blur(); document.body.focus(); assert.ok( !Sizzle.matchesSelector( tmp, ":focus" ), ":focus doesn't match tabIndex div" ); document.body.removeChild( tmp ); // Input focus/active input = document.createElement( "input" ); input.type = "text"; input.id = "focus-input"; document.body.appendChild( input ); input.focus(); // Inputs can't be focused unless the document has focus if ( document.activeElement !== input || ( document.hasFocus && !document.hasFocus() ) || ( document.querySelectorAll && !document.querySelectorAll( "input:focus" ).length ) ) { assert.ok( true, "The input was not focused. Skip checking the :focus match." ); assert.ok( true, "The input was not focused. Skip checking the :focus match." ); } else { t( "Element focused", "input:focus", [ "focus-input" ] ); assert.ok( Sizzle.matchesSelector( input, ":focus" ), ":focus matches" ); } input.blur(); // When IE is out of focus, blur does not work. Force it here. if ( document.activeElement === input ) { document.body.focus(); } assert.ok( !Sizzle.matchesSelector( input, ":focus" ), ":focus doesn't match" ); document.body.removeChild( input ); assert.deepEqual( Sizzle( "[id='select1'] *:not(:last-child), [id='select2'] *:not(:last-child)", q( "qunit-fixture" )[ 0 ] ), q( "option1a", "option1b", "option1c", "option2a", "option2b", "option2c" ), "caching system tolerates recursive selection" ); // Tokenization edge cases t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code)", [ "ap" ] ); t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code):contains(This link)", [ "ap" ] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", [ "ap" ] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", [ "ap" ] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=\\)]", [ "sndp" ] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=')']", [ "sndp" ] ); t( "Multi-pseudo", "#ap:has(*), #ap:has(*)", [ "ap" ] ); t( "Multi-positional", "#ap:gt(0), #ap:lt(1)", [ "ap" ] ); t( "Multi-pseudo with leading nonexistent id", "#nonexistent:has(*), #ap:has(*)", [ "ap" ] ); t( "Multi-positional with leading nonexistent id", "#nonexistent:gt(0), #ap:lt(1)", [ "ap" ] ); t( "Tokenization stressor", "a[class*=blog]:not(:has(*, :contains(!)), :contains(!)), br:contains(]), p:contains(]), :not(:empty):not(:parent)", [ "ap", "mark", "yahoo", "simon" ] ); } ); QUnit.test( "pseudo - :not", function( assert ) { assert.expect( 43 ); t( "Not", "a.blog:not(.link)", [ "mark" ] ); t( ":not() with :first", "#foo p:not(:first) .link", [ "simon" ] ); t( "Not - multiple", "#form option:not(:contains(Nothing),#option1b,:selected)", [ "option1c", "option1d", "option2b", "option2c", "option3d", "option3e", "option4e", "option5b", "option5c" ] ); t( "Not - recursive", "#form option:not(:not(:selected))[id^='option3']", [ "option3b", "option3c" ] ); t( ":not() failing interior", "#qunit-fixture p:not(.foo)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not() failing interior", "#qunit-fixture p:not(div.foo)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not() failing interior", "#qunit-fixture p:not(p.foo)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not() failing interior", "#qunit-fixture p:not(#blargh)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not() failing interior", "#qunit-fixture p:not(div#blargh)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not() failing interior", "#qunit-fixture p:not(p#blargh)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not Multiple", "#qunit-fixture p:not(a)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not Multiple", "#qunit-fixture p:not( a )", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not Multiple", "#qunit-fixture p:not( p )", [] ); t( ":not Multiple", "#qunit-fixture p:not(a, b)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not Multiple", "#qunit-fixture p:not(a, b, div)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( ":not Multiple", "p:not(p)", [] ); t( ":not Multiple", "p:not(a,p)", [] ); t( ":not Multiple", "p:not(p,a)", [] ); t( ":not Multiple", "p:not(a,p,b)", [] ); t( ":not Multiple", ":input:not(:image,:input,:submit)", [] ); t( ":not Multiple", "#qunit-fixture p:not(:has(a), :nth-child(1))", [ "first" ] ); t( "No element not selector", ".container div:not(.excluded) div", [] ); t( ":not() Existing attribute", "#form select:not([multiple])", [ "select1", "select2", "select5" ] ); t( ":not() Equals attribute", "#form select:not([name=select1])", [ "select2", "select3", "select4", "select5" ] ); t( ":not() Equals quoted attribute", "#form select:not([name='select1'])", [ "select2", "select3", "select4", "select5" ] ); t( ":not() Multiple Class", "#foo a:not(.blog)", [ "yahoo", "anchor2" ] ); t( ":not() Multiple Class", "#foo a:not(.link)", [ "yahoo", "anchor2" ] ); t( ":not() Multiple Class", "#foo a:not(.blog.link)", [ "yahoo", "anchor2" ] ); t( ":not chaining (compound)", "#qunit-fixture div[id]:not(:has(div, span)):not(:has(*))", [ "nothiddendivchild", "divWithNoTabIndex" ] ); t( ":not chaining (with attribute)", "#qunit-fixture form[id]:not([action$='formaction']):not(:button)", [ "lengthtest", "name-tests", "testForm", "disabled-tests" ] ); t( ":not chaining (colon in attribute)", "#qunit-fixture form[id]:not([action='form:action']):not(:button)", [ "form", "lengthtest", "name-tests", "testForm", "disabled-tests" ] ); t( ":not chaining (colon in attribute and nested chaining)", "#qunit-fixture form[id]:not([action='form:action']:button):not(:input)", [ "form", "lengthtest", "name-tests", "testForm", "disabled-tests" ] ); t( ":not chaining", "#form select:not(.select1):contains(Nothing) > option:not(option)", [] ); t( "positional :not()", "#foo p:not(:last)", [ "sndp", "en" ] ); t( "positional :not() prefix", "#foo p:not(:last) a", [ "yahoo" ] ); t( "compound positional :not()", "#foo p:not(:first, :last)", [ "en" ] ); t( "compound positional :not()", "#foo p:not(:first, :even)", [ "en" ] ); t( "compound positional :not()", "#foo p:not(:first, :odd)", [ "sap" ] ); t( "reordered compound positional :not()", "#foo p:not(:odd, :first)", [ "sap" ] ); t( "positional :not() with pre-filter", "#foo p:not([id]:first)", [ "en", "sap" ] ); t( "positional :not() with post-filter", "#foo p:not(:first[id])", [ "en", "sap" ] ); t( "positional :not() with pre-filter", "#foo p:not([lang]:first)", [ "sndp", "sap" ] ); t( "positional :not() with post-filter", "#foo p:not(:first[lang])", [ "sndp", "en", "sap" ] ); } ); QUnit.test( "pseudo - position", function( assert ) { assert.expect( 34 ); t( "First element", "#qunit-fixture p:first", [ "firstp" ] ); t( "First element(case-insensitive)", "#qunit-fixture p:fiRst", [ "firstp" ] ); t( "nth Element", "#qunit-fixture p:nth(1)", [ "ap" ] ); t( "First Element", "#qunit-fixture p:first", [ "firstp" ] ); t( "Last Element", "p:last", [ "first" ] ); t( "Even Elements", "#qunit-fixture p:even", [ "firstp", "sndp", "sap" ] ); t( "Odd Elements", "#qunit-fixture p:odd", [ "ap", "en", "first" ] ); t( "Position Equals", "#qunit-fixture p:eq(1)", [ "ap" ] ); t( "Position Equals (negative)", "#qunit-fixture p:eq(-1)", [ "first" ] ); t( "Position Greater Than", "#qunit-fixture p:gt(0)", [ "ap", "sndp", "en", "sap", "first" ] ); t( "Position Less Than", "#qunit-fixture p:lt(3)", [ "firstp", "ap", "sndp" ] ); t( "Position Less Than Big Number", "#qunit-fixture p:lt(9007199254740991)", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); t( "Check position filtering", "div#nothiddendiv:eq(0)", [ "nothiddendiv" ] ); t( "Check position filtering", "div#nothiddendiv:last", [ "nothiddendiv" ] ); t( "Check position filtering", "div#nothiddendiv:not(:gt(0))", [ "nothiddendiv" ] ); t( "Check position filtering", "#foo > :not(:first)", [ "en", "sap" ] ); t( "Check position filtering", "#qunit-fixture select > :not(:gt(2))", [ "option1a", "option1b", "option1c" ] ); t( "Check position filtering", "#qunit-fixture select:lt(2) :not(:first)", [ "option1b", "option1c", "option1d", "option2a", "option2b", "option2c", "option2d" ] ); t( "Check position filtering", "div.nothiddendiv:eq(0)", [ "nothiddendiv" ] ); t( "Check position filtering", "div.nothiddendiv:last", [ "nothiddendiv" ] ); t( "Check position filtering", "div.nothiddendiv:not(:lt(0))", [ "nothiddendiv" ] ); t( "Check element position", "#qunit-fixture div div:eq(0)", [ "nothiddendivchild" ] ); t( "Check element position", "#select1 option:eq(3)", [ "option1d" ] ); t( "Check element position", "#qunit-fixture div div:eq(10)", [ "names-group" ] ); t( "Check element position", "#qunit-fixture div div:first", [ "nothiddendivchild" ] ); t( "Check element position", "#qunit-fixture div > div:first", [ "nothiddendivchild" ] ); t( "Check element position", "#qunit-fixture div:first a:first", [ "yahoo" ] ); t( "Check element position", "#qunit-fixture div:first > p:first", [ "sndp" ] ); t( "Check element position", "div#nothiddendiv:first > div:first", [ "nothiddendivchild" ] ); t( "Chained pseudo after a pos pseudo", "#listWithTabIndex li:eq(0):contains(Rice)", [ "foodWithNegativeTabIndex" ] ); t( "Check sort order with POS and comma", "#qunit-fixture em>em>em>em:first-child,div>em:first", [ "siblingfirst", "siblinggreatgrandchild" ] ); t( "Isolated position", "#qunit-fixture :last", [ "last" ] ); assert.deepEqual( Sizzle( "*:lt(2) + *", null, [], Sizzle( "#qunit-fixture > p" ) ), q( "ap" ), "Seeded pos with trailing relative" ); // jQuery #12526 var context = jQuery( "#qunit-fixture" ).append( "<div id='jquery12526'></div>" )[ 0 ]; assert.deepEqual( Sizzle( ":last", context ), q( "jquery12526" ), "Post-manipulation positional" ); } ); QUnit.test( "pseudo - form", function( assert ) { assert.expect( 10 ); var extraTexts = jQuery( "<input id=\"impliedText\"/><input id=\"capitalText\" type=\"TEXT\">" ).appendTo( "#form" ); t( "Form element :input", "#form :input", [ "text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "search", "button", "area1", "select1", "select2", "select3", "select4", "select5", "impliedText", "capitalText" ] ); t( "Form element :radio", "#form :radio", [ "radio1", "radio2" ] ); t( "Form element :checkbox", "#form :checkbox", [ "check1", "check2" ] ); t( "Form element :text", "#form :text", [ "text1", "text2", "hidden2", "name", "impliedText", "capitalText" ] ); t( "Form element :radio:checked", "#form :radio:checked", [ "radio2" ] ); t( "Form element :checkbox:checked", "#form :checkbox:checked", [ "check1" ] ); t( "Form element :radio:checked, :checkbox:checked", "#form :radio:checked, #form :checkbox:checked", [ "radio2", "check1" ] ); t( "Selected option element", "#form option:selected", [ "option1a", "option2d", "option3b", "option3c", "option4b", "option4c", "option4d", "option5a" ] ); t( "Selected option elements are also :checked", "#form option:checked", [ "option1a", "option2d", "option3b", "option3c", "option4b", "option4c", "option4d", "option5a" ] ); t( "Hidden inputs are still :enabled", "#hidden1:enabled", [ "hidden1" ] ); extraTexts.remove(); } ); QUnit.test( "pseudo - :(dis|en)abled, explicitly disabled", function( assert ) { assert.expect( 2 ); // Set a meaningless disabled property on a common ancestor var container = document.getElementById( "disabled-tests" ); container.disabled = true; // Support: IE 6 - 11 // Unset the property where it is not meaningless if ( document.getElementById( "enabled-input" ).isDisabled ) { container.disabled = undefined; } t( "Explicitly disabled elements", "#enabled-fieldset :disabled", [ "disabled-input", "disabled-textarea", "disabled-button", "disabled-select", "disabled-optgroup", "disabled-option" ] ); t( "Enabled elements",
jquery/sizzle
9ffbb8b6e18d79bdc8cc9ee94d7b923de0661b32
Build: Update eslint-config-jquery, fix violations, fix the build task
diff --git a/Gruntfile.js b/Gruntfile.js index 076578f..45fd75b 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,285 +1,292 @@ module.exports = function( grunt ) { "use strict"; var gzip = require( "gzip-js" ), isBrowserStack = process.env.BROWSER_STACK_USERNAME && process.env.BROWSER_STACK_ACCESS_KEY, browsers = { phantom: [ "PhantomJS" ], desktop: [], android: [], ios: [], old: { firefox: [], chrome: [], safari: [], ie: [], opera: [], android: [] } }, files = { source: "src/sizzle.js", speed: "speed/speed.js", tests: "test/{data,unit}/*.js", karma: "test/karma/*.js", grunt: [ "Gruntfile.js", "tasks/*" ] }; // if Browserstack is set up, assume we can use it if ( isBrowserStack ) { // See https://github.com/jquery/sizzle/wiki/Sizzle-Documentation#browsers browsers.desktop = [ "bs_chrome-45", // shares V8 with Node.js 4 LTS "bs_chrome-70", "bs_chrome-71", "bs_firefox-52", "bs_firefox-60", // Firefox ESR "bs_firefox-63", "bs_firefox-64", "bs_edge-17", "bs_edge-18", "bs_ie-9", "bs_ie-10", "bs_ie-11", "bs_opera-56", "bs_opera-57", // Real Safari 6.1 and 7.0 are not available "bs_safari-6.0", "bs_safari-8.0", "bs_safari-9.1", "bs_safari-10.1", "bs_safari-11.1", "bs_safari-12.0" ]; browsers.ios = [ "bs_ios-5.1", "bs_ios-6.0", "bs_ios-7.0", "bs_ios-8.3", "bs_ios-9.3", "bs_ios-10.3", "bs_ios-11.4", "bs_ios-12.1" ]; browsers.android = [ "bs_android-4.0", "bs_android-4.1", "bs_android-4.2", "bs_android-4.3", "bs_android-4.4" ]; browsers.old = { firefox: [ "bs_firefox-3.6" ], chrome: [ "bs_chrome-16" ], safari: [ "bs_safari-4.0", "bs_safari-5.0", "bs_safari-5.1" ], ie: [ "bs_ie-7", "bs_ie-8" ], opera: [ "bs_opera-11.6", "bs_opera-12.16" ], android: [ "bs_android-2.3" ] }; } // Project configuration grunt.initConfig( { pkg: grunt.file.readJSON( "package.json" ), dateString: new Date().toISOString().replace( /\..*Z/, "" ), compile: { all: { dest: "dist/sizzle.js", src: "src/sizzle.js" } }, version: { files: [ "package.json", "bower.json" ] }, uglify: { all: { files: { "dist/sizzle.min.js": [ "dist/sizzle.js" ] }, options: { compress: { "hoist_funs": false, loops: false }, output: { ascii_only: true }, banner: "/*! Sizzle v<%= pkg.version %> | (c) " + "JS Foundation and other contributors | js.foundation */", sourceMap: true, sourceMapName: "dist/sizzle.min.map" } } }, "ensure_ascii": { files: [ "dist/*.js" ] }, "compare_size": { files: [ "dist/sizzle.js", "dist/sizzle.min.js" ], options: { compress: { gz: function( contents ) { return gzip.zip( contents, {} ).length; } }, cache: "dist/.sizecache.json" } }, npmcopy: { all: { options: { destPrefix: "external" }, files: { "benchmark/benchmark.js": "benchmark/benchmark.js", "benchmark/LICENSE.txt": "benchmark/LICENSE.txt", "jquery/jquery.js": "jquery/jquery.js", "jquery/MIT-LICENSE.txt": "jquery/MIT-LICENSE.txt", "qunit/qunit.js": "qunitjs/qunit/qunit.js", "qunit/qunit.css": "qunitjs/qunit/qunit.css", "qunit/LICENSE.txt": "qunitjs/LICENSE.txt", "requirejs/require.js": "requirejs/require.js", "requirejs-domready/domReady.js": "requirejs-domready/domReady.js", "requirejs-text/text.js": "requirejs-text/text.js" } } }, eslint: { options: { // See https://github.com/sindresorhus/grunt-eslint/issues/119 quiet: true }, dist: { src: "dist/sizzle.js" }, dev: { src: [ files.source, files.grunt, files.karma, files.speed, files.tests ] }, grunt: { src: files.grunt }, speed: { src: [ files.speed ] }, tests: { src: [ files.tests ] }, karma: { src: [ files.karma ] } }, jsonlint: { pkg: { src: [ "package.json" ] }, bower: { src: [ "bower.json" ] } }, karma: { options: { configFile: "test/karma/karma.conf.js", singleRun: true }, watch: { background: true, singleRun: false, browsers: browsers.phantom }, phantom: { browsers: browsers.phantom }, desktop: { browsers: browsers.desktop }, android: { browsers: browsers.android }, ios: { browsers: browsers.ios }, oldIe: { browsers: browsers.old.ie, // Support: IE <=8 only // Force use of JSONP polling transports: [ "polling" ], forceJSONP: true }, oldOpera: { browsers: browsers.old.opera }, oldFirefox: { browsers: browsers.old.firefox }, oldChrome: { browsers: browsers.old.chrome }, oldSafari: { browsers: browsers.old.safari }, oldAndroid: { browsers: browsers.old.android }, all: { browsers: browsers.phantom.concat( browsers.desktop, browsers.ios, browsers.android, browsers.old.firefox, browsers.old.chrome, browsers.old.safari, browsers.old.ie, browsers.old.opera, browsers.old.android ) } }, watch: { options: { livereload: true }, files: [ files.source, files.grunt, files.karma, files.speed, "test/**/*", "test/*.html", "{package,bower}.json" ], tasks: [ "build", "karma:watch:run" ] } } ); // Integrate Sizzle specific tasks grunt.loadTasks( "tasks" ); // Load dev dependencies require( "load-grunt-tasks" )( grunt ); grunt.registerTask( "lint", [ "jsonlint", "eslint:dev", "eslint:dist" ] ); grunt.registerTask( "start", [ "karma:watch:start", "watch" ] ); // Execute tests all browsers in sequential way, // so slow connections would not affect other runs grunt.registerTask( "tests", isBrowserStack ? [ "karma:phantom", "karma:desktop", "karma:ios", "karma:oldIe", "karma:oldFirefox", "karma:oldChrome", "karma:oldSafari", "karma:oldOpera" // See #314 :-( // "karma:android", "karma:oldAndroid" ] : "karma:phantom" ); - grunt.registerTask( "build", [ "lint", "compile", "uglify", "dist", "ensure_ascii" ] ); - grunt.registerTask( "default", [ + grunt.registerTask( "build", [ + "jsonlint", "eslint:dev", + "compile", + "uglify", + "dist", + "eslint:dist", + "ensure_ascii" + ] ); + grunt.registerTask( "default", [ "build", "tests", "compare_size", "eslint:dist" ] ); grunt.registerTask( "bower", "bowercopy" ); }; diff --git a/dist/sizzle.js b/dist/sizzle.js index 604ae2b..5bd623a 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -809,1588 +809,1588 @@ setDocument = Sizzle.setDocument = function( node ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains( preferredDoc, a ) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first ap[ i ] === preferredDoc ? -1 : bp[ i ] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, - "CHILD": function( type, what, argument, first, last ) { + "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : - function( elem, context, xml ) { + function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? - markFunction( function( seed, matches, context, xml ) { + markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : - function( elem, context, xml ) { + function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), - "last": createPositionalPseudo( function( matchIndexes, length ) { + "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), - "eq": createPositionalPseudo( function( matchIndexes, length, argument ) { + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { - addHandle( "value", function( elem, name, isXML ) { + addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } // EXPOSE var _sizzle = window.Sizzle; Sizzle.noConflict = function() { if ( window.Sizzle === Sizzle ) { window.Sizzle = _sizzle; } return Sizzle; }; if ( typeof define === "function" && define.amd ) { define( function() { return Sizzle; } ); // Sizzle requires that there be a global window in Common-JS like environments } else if ( typeof module !== "undefined" && module.exports ) { module.exports = Sizzle; } else { window.Sizzle = Sizzle; } // EXPOSE } )( window ); diff --git a/dist/sizzle.min.map b/dist/sizzle.min.map index 037121a..2003de8 100644 --- a/dist/sizzle.min.map +++ b/dist/sizzle.min.map @@ -1 +1 @@ -{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","last","simple","forward","ofType","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GAIRsB,KAAgBC,eAChBC,KACAC,EAAMD,EAAIC,IACVC,EAAaF,EAAIG,KACjBA,EAAOH,EAAIG,KACXC,EAAQJ,EAAII,MAIZC,EAAU,SAAUC,EAAMC,GAGzB,IAFA,IAAIzC,EAAI,EACP0C,EAAMF,EAAKG,OACJ3C,EAAI0C,EAAK1C,IAChB,GAAKwC,EAAMxC,KAAQyC,EAClB,OAAOzC,EAGT,OAAQ,GAGT4C,EAAW,6HAMXC,EAAa,sBAGbC,EAAa,gCAGbC,EAAa,MAAQF,EAAa,KAAOC,EAAa,OAASD,EAG9D,gBAAkBA,EAIlB,2DAA6DC,EAAa,OAC1ED,EAAa,OAEdG,EAAU,KAAOF,EAAa,wFAOAC,EAAa,eAO3CE,EAAc,IAAIC,OAAQL,EAAa,IAAK,KAC5CM,EAAQ,IAAID,OAAQ,IAAML,EAAa,8BACtCA,EAAa,KAAM,KAEpBO,EAAS,IAAIF,OAAQ,IAAML,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A,EAAGyC,UAAY,mBACiC,MAAzCzC,EAAG8E,WAAWjG,aAAc,WAEnCsB,GAAW,yBAA0B,SAAUtG,EAAMiK,EAAMtM,GAC1D,IAAMA,EACL,OAAOqC,EAAKgF,aAAciF,EAA6B,SAAvBA,EAAK/G,cAA2B,EAAI,KAOjE1F,EAAQ8C,YAAe4F,GAAQ,SAAUC,GAG9C,OAFAA,EAAGyC,UAAY,WACfzC,EAAG8E,WAAW/F,aAAc,QAAS,IACY,KAA1CiB,EAAG8E,WAAWjG,aAAc,YAEnCsB,GAAW,QAAS,SAAUtG,EAAMiK,EAAMtM,GACzC,IAAMA,GAAyC,UAAhCqC,EAAKiD,SAASC,cAC5B,OAAOlD,EAAKiT,eAOT/M,GAAQ,SAAUC,GACvB,OAAwC,MAAjCA,EAAGnB,aAAc,eAExBsB,GAAWnG,EAAU,SAAUH,EAAMiK,EAAMtM,GAC1C,IAAIuM,EACJ,IAAMvM,EACL,OAAwB,IAAjBqC,EAAMiK,GAAkBA,EAAK/G,eACjCgH,EAAMlK,EAAKwI,iBAAkByB,KAAYC,EAAIE,UAC9CF,EAAIrE,MACJ,OAML,IAAIqN,GAAU5V,EAAOuG,OAErBA,GAAOsP,WAAa,WAKnB,OAJK7V,EAAOuG,SAAWA,KACtBvG,EAAOuG,OAASqP,IAGVrP,IAGe,mBAAXuP,QAAyBA,OAAOC,IAC3CD,OAAQ,WACP,OAAOvP,KAIqB,oBAAXyP,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU1P,GAEjBvG,EAAOuG,OAASA,GA50EjB,CAi1EKvG","file":"sizzle.min.js"} \ No newline at end of file +{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","pushNative","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","_argument","last","simple","forward","ofType","_context","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","_matchIndexes","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","_name","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAYA,GACZ,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GAIRsB,KAAgBC,eAChBC,KACAC,EAAMD,EAAIC,IACVC,EAAaF,EAAIG,KACjBA,EAAOH,EAAIG,KACXC,EAAQJ,EAAII,MAIZC,EAAU,SAAUC,EAAMC,GAGzB,IAFA,IAAIzC,EAAI,EACP0C,EAAMF,EAAKG,OACJ3C,EAAI0C,EAAK1C,IAChB,GAAKwC,EAAMxC,KAAQyC,EAClB,OAAOzC,EAGT,OAAQ,GAGT4C,EAAW,6HAMXC,EAAa,sBAGbC,EAAa,gCAGbC,EAAa,MAAQF,EAAa,KAAOC,EAAa,OAASD,EAG9D,gBAAkBA,EAIlB,2DAA6DC,EAAa,OAC1ED,EAAa,OAEdG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/package-lock.json +++ b/package-lock.json @@ -1073,1027 +1073,1027 @@ "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { "ms": "2.0.0" } }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "decode-uri-component": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", "dev": true }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", "dev": true }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", "dev": true, "requires": { "is-descriptor": "^1.0.2", "isobject": "^3.0.1" }, "dependencies": { "is-accessor-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-data-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-descriptor": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { "is-accessor-descriptor": "^1.0.0", "is-data-descriptor": "^1.0.0", "kind-of": "^6.0.2" } }, "isobject": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", "dev": true }, "kind-of": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", "dev": true } } }, "deflate-js": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/deflate-js/-/deflate-js-0.2.3.tgz", "integrity": "sha1-+Fq7WOvFFRowYUdHPVfD5PfkQms=", "dev": true }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", "dev": true }, "depd": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", "dev": true }, "di": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", "dev": true }, "doctrine": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", "dev": true, "requires": { "esutils": "^2.0.2" } }, "dom-serialize": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", "dev": true, "requires": { "custom-event": "~1.0.0", "ent": "~2.2.0", "extend": "^3.0.0", "void-elements": "^2.0.0" } }, "duplexer2": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", "integrity": "sha1-ixLauHjA1p4+eJEFFmKjL8a93ME=", "dev": true, "requires": { "readable-stream": "^2.0.2" }, "dependencies": { "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "requires": { "safe-buffer": "~5.1.0" } } } }, "ecc-jsbn": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", "dev": true, "requires": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" } }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", "dev": true }, "emoji-regex": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, "encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", "dev": true }, "engine.io": { "version": "1.6.10", "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-1.6.10.tgz", "integrity": "sha1-+H2E4b0h0aLsf43u8MYgVKzfsno=", "dev": true, "requires": { "accepts": "1.1.4", "base64id": "0.1.0", "debug": "2.2.0", "engine.io-parser": "1.2.4", "ws": "1.0.1" }, "dependencies": { "debug": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", "dev": true, "requires": { "ms": "0.7.1" } }, "ms": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", "dev": true } } }, "engine.io-client": { "version": "1.6.9", "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-1.6.9.tgz", "integrity": "sha1-HWrUgEilCDyVCWlDsp0279shJAE=", "dev": true, "requires": { "component-emitter": "1.1.2", "component-inherit": "0.0.3", "debug": "2.2.0", "engine.io-parser": "1.2.4", "has-cors": "1.1.0", "indexof": "0.0.1", "parsejson": "0.0.1", "parseqs": "0.0.2", "parseuri": "0.0.4", "ws": "1.0.1", "xmlhttprequest-ssl": "1.5.1", "yeast": "0.1.2" }, "dependencies": { "component-emitter": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", "dev": true }, "debug": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", "dev": true, "requires": { "ms": "0.7.1" } }, "ms": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", "dev": true } } }, "engine.io-parser": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-1.2.4.tgz", "integrity": "sha1-4Il7C/FOeS1M0qWVBVORnFaUjEI=", "dev": true, "requires": { "after": "0.8.1", "arraybuffer.slice": "0.0.6", "base64-arraybuffer": "0.1.2", "blob": "0.0.4", "has-binary": "0.1.6", "utf8": "2.1.0" }, "dependencies": { "has-binary": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/has-binary/-/has-binary-0.1.6.tgz", "integrity": "sha1-JTJvOc+k9hath4eJTjryz7x7bhA=", "dev": true, "requires": { "isarray": "0.0.1" } } } }, "ent": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", "dev": true }, "error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "dev": true, "requires": { "is-arrayish": "^0.2.1" } }, "es6-promise": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.0.5.tgz", "integrity": "sha1-eILzCt3lskDM+n99eMVIMwlRrkI=", "dev": true }, "es6-promisify": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", "dev": true, "requires": { "es6-promise": "^4.0.3" } }, "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", "dev": true }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "eslint": { "version": "5.16.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.16.0.tgz", "integrity": "sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", "ajv": "^6.9.1", "chalk": "^2.1.0", "cross-spawn": "^6.0.5", "debug": "^4.0.1", "doctrine": "^3.0.0", "eslint-scope": "^4.0.3", "eslint-utils": "^1.3.1", "eslint-visitor-keys": "^1.0.0", "espree": "^5.0.1", "esquery": "^1.0.1", "esutils": "^2.0.2", "file-entry-cache": "^5.0.1", "functional-red-black-tree": "^1.0.1", "glob": "^7.1.2", "globals": "^11.7.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "inquirer": "^6.2.2", "js-yaml": "^3.13.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.3.0", "lodash": "^4.17.11", "minimatch": "^3.0.4", "mkdirp": "^0.5.1", "natural-compare": "^1.4.0", "optionator": "^0.8.2", "path-is-inside": "^1.0.2", "progress": "^2.0.0", "regexpp": "^2.0.1", "semver": "^5.5.1", "strip-ansi": "^4.0.0", "strip-json-comments": "^2.0.1", "table": "^5.2.3", "text-table": "^0.2.0" }, "dependencies": { "ajv": { "version": "6.10.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", "dev": true, "requires": { "fast-deep-equal": "^2.0.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "ansi-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", "dev": true }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "requires": { "color-convert": "^1.9.0" } }, "argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "requires": { "sprintf-js": "~1.0.2" } }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "dev": true, "requires": { "ms": "^2.1.1" } }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, "glob": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "js-yaml": { "version": "3.13.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "dev": true, "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, "progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", "dev": true }, "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { "ansi-regex": "^3.0.0" } }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", "dev": true }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "requires": { "has-flag": "^3.0.0" } } } }, "eslint-config-jquery": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/eslint-config-jquery/-/eslint-config-jquery-1.0.1.tgz", - "integrity": "sha1-p/3Xu8mKZUvHcTnB9VNfrfDfI8g=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-config-jquery/-/eslint-config-jquery-2.0.0.tgz", + "integrity": "sha512-HrUTma5Ty6A91M3dTWz3Ot7YnpbsDQGIQDI8JyLKiuUltVXuKCs3yC7uHugp5/0RfYAPLisxHv7giNGvaqM4CA==", "dev": true }, "eslint-scope": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", "dev": true, "requires": { "esrecurse": "^4.1.0", "estraverse": "^4.1.1" } }, "eslint-utils": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.3.1.tgz", "integrity": "sha512-Z7YjnIldX+2XMcjr7ZkgEsOj/bREONV60qYeB/bjMAqqqZ4zxKyWX+BOUkdmRmA9riiIPVvo5x86m5elviOk0Q==", "dev": true }, "eslint-visitor-keys": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", "dev": true }, "espree": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/espree/-/espree-5.0.1.tgz", "integrity": "sha512-qWAZcWh4XE/RwzLJejfcofscgMc9CamR6Tn1+XRXNzrvUSSbiAjGOI/fggztjIi7y9VLPqnICMIPiGyr8JaZ0A==", "dev": true, "requires": { "acorn": "^6.0.7", "acorn-jsx": "^5.0.0", "eslint-visitor-keys": "^1.0.0" } }, "esprima": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/esprima/-/esprima-1.0.4.tgz", "integrity": "sha1-n1V+CPw7TSbs6d00+Pv0drYlha0=", "dev": true }, "esquery": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", "dev": true, "requires": { "estraverse": "^4.0.0" } }, "esrecurse": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", "dev": true, "requires": { "estraverse": "^4.1.0" } }, "estraverse": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", "dev": true }, "esutils": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", "dev": true }, "eventemitter2": { "version": "0.4.14", "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=", "dev": true }, "eventemitter3": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==", "dev": true }, "exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, "expand-braces": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/expand-braces/-/expand-braces-0.1.2.tgz", "integrity": "sha1-SIsdHSRRyz06axks/AMPRMWFX+o=", "dev": true, "requires": { "array-slice": "^0.2.3", "array-unique": "^0.2.1", "braces": "^0.1.2" }, "dependencies": { "braces": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/braces/-/braces-0.1.5.tgz", "integrity": "sha1-wIVxEIUpHYt1/ddOqw+FlygHEeY=", "dev": true, "requires": { "expand-range": "^0.1.0" } }, "expand-range": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-0.1.1.tgz", "integrity": "sha1-TLjtoJk8pW+k9B/ELzy7TMrf8EQ=", "dev": true, "requires": { "is-number": "^0.1.1", "repeat-string": "^0.2.2" } }, "is-number": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-number/-/is-number-0.1.1.tgz", "integrity": "sha1-aaevEWlj1HIG7JvZtIoUIW8eOAY=", "dev": true }, "repeat-string": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-0.2.2.tgz", "integrity": "sha1-x6jTI2BoNiBZp+RlH8aITosftK4=", "dev": true } } }, "expand-brackets": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", "dev": true, "requires": { "is-posix-bracket": "^0.1.0" } }, "expand-range": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", "dev": true, "requires": { "fill-range": "^2.1.0" } }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, "extend-shallow": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", "dev": true, "requires": { "assign-symbols": "^1.0.0", "is-extendable": "^1.0.1" }, "dependencies": { "is-extendable": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", "dev": true, "requires": { "is-plain-object": "^2.0.4" } } } }, "external-editor": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", "dev": true, "requires": { "chardet": "^0.7.0", "iconv-lite": "^0.4.24", "tmp": "^0.0.33" }, "dependencies": { "iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "requires": { "safer-buffer": ">= 2.1.2 < 3" } }, "tmp": { "version": "0.0.33", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", "dev": true, "requires": { "os-tmpdir": "~1.0.2" } } } }, "extglob": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", "dev": true, "requires": { "is-extglob": "^1.0.0" } }, "extract-zip": { "version": "1.6.7", "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz", "integrity": "sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k=", "dev": true, "requires": { "concat-stream": "1.6.2", "debug": "2.6.9", "mkdirp": "0.5.1", "yauzl": "2.4.1" } }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", "dev": true }, "fast-deep-equal": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", "dev": true }, "fast-json-stable-stringify": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", "dev": true }, "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, "faye-websocket": { "version": "0.10.0", "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", "dev": true, "requires": { "websocket-driver": ">=0.5.1" } }, "fd-slicer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", "dev": true, "requires": { "pend": "~1.2.0" } }, "figures": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5", "object-assign": "^4.1.0" } }, "file-entry-cache": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", "dev": true, "requires": { "flat-cache": "^2.0.1" } }, "filename-regex": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", "dev": true }, "fill-range": { "version": "2.2.4", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz", "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", "dev": true, "requires": { "is-number": "^2.1.0", "isobject": "^2.0.0", "randomatic": "^3.0.0", "repeat-element": "^1.1.2", "repeat-string": "^1.5.2" } }, "finalhandler": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", "dev": true, "requires": { "debug": "2.6.9", "encodeurl": "~1.0.1", "escape-html": "~1.0.3", "on-finished": "~2.3.0", "parseurl": "~1.3.2", "statuses": "~1.3.1", "unpipe": "~1.0.0" }, "dependencies": { "statuses": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", "dev": true } } }, "find-up": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { "path-exists": "^2.0.0", "pinkie-promise": "^2.0.0" } }, "findup-sync": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.1.3.tgz", "integrity": "sha1-fz56l7gjksZTvwZYm9hRkOk8NoM=", "dev": true, "requires": { "glob": "~3.2.9", "lodash": "~2.4.1" }, "dependencies": { "glob": { "version": "3.2.11", "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.11.tgz", "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", "dev": true, "requires": { "inherits": "2", "minimatch": "0.3" } }, "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true }, "minimatch": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz", "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } } } }, "flat-cache": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", "dev": true, "requires": { "flatted": "^2.0.0", "rimraf": "2.6.3", "write": "1.0.3" }, "dependencies": { "glob": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, "rimraf": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", "dev": true, "requires": { "glob": "^7.1.3" } } } }, "flatted": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.0.tgz", "integrity": "sha512-R+H8IZclI8AAkSBRQJLVOsxwAoHd6WC40b4QTNWIjzAa6BXOBfQcM587MXDTVPeYaopFNWHUFLx7eNmHDSxMWg==", "dev": true }, "follow-redirects": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz", "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==", "dev": true, "requires": { "debug": "^3.2.6" }, "dependencies": { "debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", "dev": true, "requires": { "ms": "^2.1.1" } }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true } } }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", "dev": true }, "for-own": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", "dev": true, "requires": { "for-in": "^1.0.1" } }, "forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", "dev": true }, "form-data": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.1.4.tgz", "integrity": "sha1-M8GDrPGTJ27KqYFDpp6Uv+4XUNE=", "dev": true, "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.5", "mime-types": "^2.1.12" } }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", "dev": true, "requires": { "map-cache": "^0.2.2" } }, "fs-access": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fs-access/-/fs-access-1.0.1.tgz", "integrity": "sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o=", "dev": true, "requires": { "null-check": "^1.0.0" } }, "fs-extra": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-1.0.0.tgz", "integrity": "sha1-zTzl9+fLYUWIP8rjGR6Yd/hYeVA=", diff --git a/package.json b/package.json index 1c51bc5..4a83d14 100644 --- a/package.json +++ b/package.json @@ -1,85 +1,85 @@ { "title": "Sizzle", "name": "sizzle", "version": "2.3.5-pre", "description": "A pure-JavaScript, bottom-up CSS selector engine designed to be easily dropped in to a host library.", "keywords": [ "sizzle", "javascript", "CSS", "selector", "jquery" ], "homepage": "https://sizzlejs.com", "author": { "name": "JS Foundation and other contributors", "url": "https://github.com/jquery/sizzle/blob/2.3.4/AUTHORS.txt" }, "repository": { "type": "git", "url": "https://github.com/jquery/sizzle.git" }, "bugs": { "url": "https://github.com/jquery/sizzle/issues" }, "license": "MIT", "files": [ "AUTHORS.txt", "LICENSE.txt", "dist/sizzle.js", "dist/sizzle.min.js", "dist/sizzle.min.map" ], "main": "dist/sizzle.js", "dependencies": {}, "devDependencies": { "benchmark": "2.1.4", "commitplease": "2.7.10", - "eslint-config-jquery": "1.0.1", + "eslint-config-jquery": "2.0.0", "grunt": "0.4.5", "grunt-cli": "0.1.13", "grunt-compare-size": "0.4.2", "grunt-contrib-qunit": "2.0.0", "grunt-contrib-uglify": "3.0.1", "grunt-contrib-watch": "1.0.0", "grunt-eslint": "21.0.0", "grunt-git-authors": "3.2.0", "grunt-jsonlint": "1.1.0", "grunt-karma": "2.0.0", "grunt-npmcopy": "0.1.0", "gzip-js": "0.3.2", "jquery": "1.9.1", "karma": "1.3.0", "karma-browserstack-launcher": "1.3.0", "karma-chrome-launcher": "2.2.0", "karma-firefox-launcher": "1.0.1", "karma-html2js-preprocessor": "1.1.0", "karma-phantomjs-launcher": "1.0.4", "karma-qunit": "1.2.1", "load-grunt-tasks": "3.5.2", "phantomjs-prebuilt": "2.1.15", "qunitjs": "1.23.1", "requirejs": "2.3.5", "requirejs-domready": "2.0.3", "requirejs-text": "2.0.15" }, "scripts": { "build": "npm install && grunt", "start": "grunt start", "test": "grunt test" }, "commitplease": { "components": [ "Misc", "Docs", "Tests", "Build", "Release", "Core", "Tokenize", "Compile", "Selector", "SetDocument" ] } } diff --git a/src/sizzle.js b/src/sizzle.js index 8dfbdd6..2bb9065 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -809,1588 +809,1588 @@ setDocument = Sizzle.setDocument = function( node ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains( preferredDoc, a ) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first ap[ i ] === preferredDoc ? -1 : bp[ i ] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, - "CHILD": function( type, what, argument, first, last ) { + "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : - function( elem, context, xml ) { + function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? - markFunction( function( seed, matches, context, xml ) { + markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : - function( elem, context, xml ) { + function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), - "last": createPositionalPseudo( function( matchIndexes, length ) { + "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), - "eq": createPositionalPseudo( function( matchIndexes, length, argument ) { + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { - addHandle( "value", function( elem, name, isXML ) { + addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } // EXPOSE var _sizzle = window.Sizzle; Sizzle.noConflict = function() { if ( window.Sizzle === Sizzle ) { window.Sizzle = _sizzle; } return Sizzle; }; if ( typeof define === "function" && define.amd ) { define( function() { return Sizzle; } ); // Sizzle requires that there be a global window in Common-JS like environments } else if ( typeof module !== "undefined" && module.exports ) { module.exports = Sizzle; } else { window.Sizzle = Sizzle; } // EXPOSE } )( window );
jquery/sizzle
7d92424c1a65a367a45034803e9de97462ea42e5
Core: Throw a better error when documentElement is missing
diff --git a/src/sizzle.js b/src/sizzle.js index 66b8577..648136a 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -70,1025 +70,1025 @@ var i, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = (elem.ownerDocument || elem).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + if ( doc === document || doc.nodeType !== 9 ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) {
jquery/sizzle
f27f9ffc9f8288cbb8cfed4d7735bdf42f2945ce
Release: Fix AUTHORS.txt
diff --git a/AUTHORS.txt b/AUTHORS.txt index ad68a50..7f52a5e 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -1,64 +1,65 @@ -Running "authors" task +Authors ordered by first contribution + John Resig <jeresig@gmail.com> Cheah Chu Yeow <chuyeow@gmail.com> Andrew Chalkley <andrew@chalkley.org> Fabio Buffoni <fabio.buffoni@bitmaster.it> Stefan Bauckmeier  <stefan@bauckmeier.de> Brandon Aaron <brandon.aaron@gmail.com> Anton Kovalyov <anton@kovalyov.net> Dušan B. Jovanovic <dbjdbj@gmail.com> Riccardo De Agostini <rdeago@gmail.com> Fabian Jakobs <fabian.jakobs@web.de> Karl Swedberg <kswedberg@gmail.com> Jake Archibald <jake.archibald@bbc.co.uk> Colin Snover <github.com@zetafleet.com> Anton Matzneller <obhvsbypqghgc@gmail.com> Dave Methvin <dave.methvin@gmail.com> Corey Frang <gnarf@gnarf.net> Mathias Bynens <mathias@qiwi.be> John Firebaugh <john_firebaugh@us.ibm.com> Timmy Willison <timmywillisn@gmail.com> Mike Sherov <mike.sherov@gmail.com> Rock Hymas <rock@fogcreek.com> Yehuda Katz <wycats@gmail.com> Jörn Zaefferer <joern.zaefferer@gmail.com> Richard Gibson <richard.gibson@gmail.com> Vitya Muhachev <vic99999@yandex.ru> Henri Wiechers <hwiechers@gmail.com> Alan Plum <github@ap.apsq.de> Chad Killingsworth <chadkillingsworth@missouristate.edu> Markus Staab <markus.staab@redaxo.de> Timo Tijhof <krinklemail@gmail.com> Diego Tres <diegotres@gmail.com> Jonathan Sampson <jjdsampson@gmail.com> Pascal Borreli <pascal@borreli.com> Daniel Herman <daniel.c.herman@gmail.com> Frederic Junod <frederic.junod@camptocamp.com> Mitch Foley <mitch@thefoley.net> Scott González <scott.gonzalez@gmail.com> Oleg Gaidarenko <markelog@gmail.com> Dan Burzo <danburzo@gmail.com> Goare Mao <mygoare@gmail.com> Dongseok Paeng <dongseok83.paeng@lge.com> Michał Gołębiowski-Owczarek <m.goleb@gmail.com> Philip Jägenstedt <philip@foolip.org> Chris Antaki <ChrisAntaki@gmail.com> Benjamin Tan <demoneaux@gmail.com> T.J. Crowder <tj.crowder@farsightsoftware.com> Anne-Gaelle Colom <coloma@westminster.ac.uk> Neftaly Hernandez <neftaly.hernandez@gmail.com> Jörn Wagner <joern.wagner@explicatis.com> Chris Rebert <code@rebertia.com> Colin Frick <colin@bash.li> John-David Dalton <john.david.dalton@gmail.com> Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com> Steve Mao <maochenyan@gmail.com> Tom von Clef <thomas.vonclef@gmail.com> Josh Soref <apache@soref.com> Saptak Sengupta <saptak013@gmail.com> Jon Dufresne <jon.dufresne@gmail.com> Andrey Meshkov <ay.meshkov@gmail.com> Sébastien Règne <regseb@users.noreply.github.com> Andrey Meshkov <am@adguard.com> Siddharth Dungarwal <sd5869@gmail.com> wartmanm <3869625+wartmanm@users.noreply.github.com>
jquery/sizzle
66f59e690521bdc38c79b33d94900bca9d7b87aa
Build: Updating the master version to 2.3.5-pre.
diff --git a/package.json b/package.json index 2f5da0d..35ee503 100644 --- a/package.json +++ b/package.json @@ -1,85 +1,85 @@ { "title": "Sizzle", "name": "sizzle", - "version": "2.3.4", + "version": "2.3.5-pre", "description": "A pure-JavaScript, bottom-up CSS selector engine designed to be easily dropped in to a host library.", "keywords": [ "sizzle", "javascript", "CSS", "selector", "jquery" ], "homepage": "https://sizzlejs.com", "author": { "name": "JS Foundation and other contributors", "url": "https://github.com/jquery/sizzle/blob/2.3.4/AUTHORS.txt" }, "repository": { "type": "git", "url": "https://github.com/jquery/sizzle.git" }, "bugs": { "url": "https://github.com/jquery/sizzle/issues" }, "license": "MIT", "files": [ "AUTHORS.txt", "LICENSE.txt", "dist/sizzle.js", "dist/sizzle.min.js", "dist/sizzle.min.map" ], "main": "dist/sizzle.js", "dependencies": {}, "devDependencies": { "benchmark": "2.1.4", "commitplease": "2.7.10", "grunt": "0.4.5", "grunt-cli": "0.1.13", "grunt-compare-size": "0.4.2", "grunt-contrib-jshint": "1.1.0", "grunt-contrib-qunit": "2.0.0", "grunt-contrib-uglify": "3.0.1", "grunt-contrib-watch": "1.0.0", "grunt-git-authors": "3.2.0", "grunt-jscs": "0.6.2", "grunt-jsonlint": "1.1.0", "grunt-karma": "2.0.0", "grunt-npmcopy": "0.1.0", "gzip-js": "0.3.2", "jquery": "1.9.1", "karma": "1.3.0", "karma-browserstack-launcher": "1.3.0", "karma-chrome-launcher": "2.2.0", "karma-firefox-launcher": "1.0.1", "karma-html2js-preprocessor": "1.1.0", "karma-phantomjs-launcher": "1.0.4", "karma-qunit": "1.2.1", "load-grunt-tasks": "3.5.2", "phantomjs-prebuilt": "2.1.15", "qunitjs": "1.23.1", "requirejs": "2.3.5", "requirejs-domready": "2.0.3", "requirejs-text": "2.0.15" }, "scripts": { "build": "npm install && grunt", "start": "grunt start", "test": "grunt test" }, "commitplease": { "components": [ "Misc", "Docs", "Tests", "Build", "Release", "Core", "Tokenize", "Compile", "Selector", "SetDocument" ] } }
jquery/sizzle
1734d4b26e6170bbcb6ab26cfcf209ed40f6e24e
Release: Update version to 2.3.4
diff --git a/bower.json b/bower.json index 68b0659..c908c13 100644 --- a/bower.json +++ b/bower.json @@ -1,25 +1,26 @@ { "name": "sizzle", "main": "./dist/sizzle.js", "license": "MIT", "ignore": [ "**/.*", "package.json", "bower.json", "speed", "Makefile", "*.md", "*.txt", "!LICENSE.txt", "src", "test", "Gruntfile.js" ], "keywords": [ "sizzle", "javascript", "CSS", "selector", "jquery" - ] + ], + "version": "2.3.4" } diff --git a/changelog b/changelog new file mode 100644 index 0000000..a50ab2f --- /dev/null +++ b/changelog @@ -0,0 +1,27 @@ +* 2.3.4 ([a04b7c5](https://github.com/jquery/sizzle/commit/a04b7c5db3b1d3c5a17265127d50e9ea9c5be5f0)) +* Build: Restore ASCII-only output ([5dfff27](https://github.com/jquery/sizzle/commit/5dfff27be7b3f398e2bad246e83cfa3582c119a7)) +* Core: Avoid unnecessary pre-qSA DOM manipulation ([#430](https://github.com/jquery/sizzle/issues/430), [71fe25c](https://github.com/jquery/sizzle/commit/71fe25c4c9a10d8827b845d398ca8fb7da163749)) +* Core: Stop changing matchesSelector input ([#408](https://github.com/jquery/sizzle/issues/408), [#406](https://github.com/jquery/sizzle/issues/406), [8bda6c9](https://github.com/jquery/sizzle/commit/8bda6c95617777ea596bf54636b27548af69d086)) +* Misc: Update isXML to recognize HTML-embedded elements ([#378](https://github.com/jquery/sizzle/issues/378), [26a1f3f](https://github.com/jquery/sizzle/commit/26a1f3f6f156cb687d0d7adc7bf79f0e5454811a)) +* Release: Add jquery-release script ([686f08d](https://github.com/jquery/sizzle/commit/686f08dc3493e2e1ed3d97e4e3f80f158b1c94c8)) +* Selector: Fix nonnativeSelectorCache ([#418](https://github.com/jquery/sizzle/issues/418), [3116795](https://github.com/jquery/sizzle/commit/3116795bba9a0c3d624e0718006b25aa5568d4cb)) +* Selector: Prevent seeded invocations from cutting off the qSA path ([#393](https://github.com/jquery/sizzle/issues/393), [eabce51](https://github.com/jquery/sizzle/commit/eabce51ea7360c4507da2eeaec2633378de4ec8d)) +* Selector: Stop using innerText in :contains ([#335](https://github.com/jquery/sizzle/issues/335), [67e9691](https://github.com/jquery/sizzle/commit/67e9691e8689b824387affb9da06dc663da63598)) +* Selector: Only fieldset ancestors can :disable form elements ([abde99f](https://github.com/jquery/sizzle/commit/abde99f6dc2ed3d489a6d7a52f3df9774be16a32)) +* Selector: Optimize ":lt(bigNumber)" ([1c0c330](https://github.com/jquery/sizzle/commit/1c0c33066f053e62ac268658f65e7d912f3bdb0d)) + + + +--- Issue List --- +#430 querySelectorAll workaround is not always needed +#418 Selector: fix nonnativeSelectorCache +#408 Selectors with escaped = characters gaining extra single-quotes through filter(). +#406 Edge 15 fails the matchesSelector "attribute-equals non-value" test +#393 Performance impact: sizzle don't use querySelectorAll for specific selector after using $('...').filter('selector') +#378 Sizzle.isXML misidentifies embedded SVG +#377 Travis has been broken for a long time +#362 Error when testing on oldIE +#335 pseudo contains uses innerText +#333 ID selectors provide no filtering benefit at all in oldIE +#314 Browserstack and android devices +#305 Mobile devices are often not getting captured on Travis diff --git a/dist/sizzle.js b/dist/sizzle.js index 1065e13..414d172 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -1,521 +1,521 @@ /*! - * Sizzle CSS Selector Engine v2.3.4-pre + * Sizzle CSS Selector Engine v2.3.4 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * - * Date: 2019-01-14 + * Date: 2019-04-08 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } diff --git a/dist/sizzle.min.js b/dist/sizzle.min.js index 0e403e4..fdbef69 100644 --- a/dist/sizzle.min.js +++ b/dist/sizzle.min.js @@ -1,3 +1,3 @@ -/*! Sizzle v2.3.4-pre | (c) JS Foundation and other contributors | js.foundation */ +/*! Sizzle v2.3.4 | (c) JS Foundation and other contributors | js.foundation */ !function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),S=ae(),A=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); //# sourceMappingURL=sizzle.min.map \ No newline at end of file diff --git a/package.json b/package.json index 5505e16..2f5da0d 100644 --- a/package.json +++ b/package.json @@ -1,85 +1,85 @@ { "title": "Sizzle", "name": "sizzle", - "version": "2.3.4-pre", + "version": "2.3.4", "description": "A pure-JavaScript, bottom-up CSS selector engine designed to be easily dropped in to a host library.", "keywords": [ "sizzle", "javascript", "CSS", "selector", "jquery" ], "homepage": "https://sizzlejs.com", "author": { "name": "JS Foundation and other contributors", - "url": "https://github.com/jquery/sizzle/blob/master/AUTHORS.txt" + "url": "https://github.com/jquery/sizzle/blob/2.3.4/AUTHORS.txt" }, "repository": { "type": "git", "url": "https://github.com/jquery/sizzle.git" }, "bugs": { "url": "https://github.com/jquery/sizzle/issues" }, "license": "MIT", "files": [ "AUTHORS.txt", "LICENSE.txt", "dist/sizzle.js", "dist/sizzle.min.js", "dist/sizzle.min.map" ], "main": "dist/sizzle.js", "dependencies": {}, "devDependencies": { "benchmark": "2.1.4", "commitplease": "2.7.10", "grunt": "0.4.5", "grunt-cli": "0.1.13", "grunt-compare-size": "0.4.2", "grunt-contrib-jshint": "1.1.0", "grunt-contrib-qunit": "2.0.0", "grunt-contrib-uglify": "3.0.1", "grunt-contrib-watch": "1.0.0", "grunt-git-authors": "3.2.0", "grunt-jscs": "0.6.2", "grunt-jsonlint": "1.1.0", "grunt-karma": "2.0.0", "grunt-npmcopy": "0.1.0", "gzip-js": "0.3.2", "jquery": "1.9.1", "karma": "1.3.0", "karma-browserstack-launcher": "1.3.0", "karma-chrome-launcher": "2.2.0", "karma-firefox-launcher": "1.0.1", "karma-html2js-preprocessor": "1.1.0", "karma-phantomjs-launcher": "1.0.4", "karma-qunit": "1.2.1", "load-grunt-tasks": "3.5.2", "phantomjs-prebuilt": "2.1.15", "qunitjs": "1.23.1", "requirejs": "2.3.5", "requirejs-domready": "2.0.3", "requirejs-text": "2.0.15" }, "scripts": { "build": "npm install && grunt", "start": "grunt start", "test": "grunt test" }, "commitplease": { "components": [ "Misc", "Docs", "Tests", "Build", "Release", "Core", "Tokenize", "Compile", "Selector", "SetDocument" ] } }
jquery/sizzle
3ec907866c44720e77ea23a12be6e5ff88bf86b6
Release: Update AUTHORS.txt
diff --git a/AUTHORS.txt b/AUTHORS.txt index a26aa85..ad68a50 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -1,60 +1,64 @@ -Authors ordered by first contribution - +Running "authors" task John Resig <jeresig@gmail.com> Cheah Chu Yeow <chuyeow@gmail.com> Andrew Chalkley <andrew@chalkley.org> Fabio Buffoni <fabio.buffoni@bitmaster.it> Stefan Bauckmeier  <stefan@bauckmeier.de> Brandon Aaron <brandon.aaron@gmail.com> Anton Kovalyov <anton@kovalyov.net> Dušan B. Jovanovic <dbjdbj@gmail.com> Riccardo De Agostini <rdeago@gmail.com> Fabian Jakobs <fabian.jakobs@web.de> Karl Swedberg <kswedberg@gmail.com> Jake Archibald <jake.archibald@bbc.co.uk> Colin Snover <github.com@zetafleet.com> Anton Matzneller <obhvsbypqghgc@gmail.com> Dave Methvin <dave.methvin@gmail.com> Corey Frang <gnarf@gnarf.net> Mathias Bynens <mathias@qiwi.be> John Firebaugh <john_firebaugh@us.ibm.com> Timmy Willison <timmywillisn@gmail.com> Mike Sherov <mike.sherov@gmail.com> Rock Hymas <rock@fogcreek.com> Yehuda Katz <wycats@gmail.com> Jörn Zaefferer <joern.zaefferer@gmail.com> Richard Gibson <richard.gibson@gmail.com> Vitya Muhachev <vic99999@yandex.ru> Henri Wiechers <hwiechers@gmail.com> Alan Plum <github@ap.apsq.de> Chad Killingsworth <chadkillingsworth@missouristate.edu> Markus Staab <markus.staab@redaxo.de> Timo Tijhof <krinklemail@gmail.com> Diego Tres <diegotres@gmail.com> Jonathan Sampson <jjdsampson@gmail.com> Pascal Borreli <pascal@borreli.com> Daniel Herman <daniel.c.herman@gmail.com> Frederic Junod <frederic.junod@camptocamp.com> Mitch Foley <mitch@thefoley.net> Scott González <scott.gonzalez@gmail.com> Oleg Gaidarenko <markelog@gmail.com> Dan Burzo <danburzo@gmail.com> Goare Mao <mygoare@gmail.com> Dongseok Paeng <dongseok83.paeng@lge.com> Michał Gołębiowski-Owczarek <m.goleb@gmail.com> Philip Jägenstedt <philip@foolip.org> Chris Antaki <ChrisAntaki@gmail.com> Benjamin Tan <demoneaux@gmail.com> T.J. Crowder <tj.crowder@farsightsoftware.com> Anne-Gaelle Colom <coloma@westminster.ac.uk> Neftaly Hernandez <neftaly.hernandez@gmail.com> Jörn Wagner <joern.wagner@explicatis.com> Chris Rebert <code@rebertia.com> Colin Frick <colin@bash.li> John-David Dalton <john.david.dalton@gmail.com> Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com> Steve Mao <maochenyan@gmail.com> Tom von Clef <thomas.vonclef@gmail.com> Josh Soref <apache@soref.com> Saptak Sengupta <saptak013@gmail.com> Jon Dufresne <jon.dufresne@gmail.com> +Andrey Meshkov <ay.meshkov@gmail.com> +Sébastien Règne <regseb@users.noreply.github.com> +Andrey Meshkov <am@adguard.com> +Siddharth Dungarwal <sd5869@gmail.com> +wartmanm <3869625+wartmanm@users.noreply.github.com>
jquery/sizzle
30eae9b4c758254597ea33f32a90834f062a4f83
Build: Update dependencies
diff --git a/package-lock.json b/package-lock.json index 46c230f..5a7ca61 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5321 +1,6320 @@ { "name": "sizzle", "version": "2.3.4-pre", "lockfileVersion": 1, "requires": true, "dependencies": { "JSV": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/JSV/-/JSV-4.0.2.tgz", "integrity": "sha1-0Hf2glVx+CEy+d/67Vh7QCn+/1c=", "dev": true }, "abbrev": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.0.tgz", - "integrity": "sha1-0FVMIlZjbi9W58LlrRg/hZQo2B8=", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", "dev": true }, "accepts": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.1.4.tgz", "integrity": "sha1-1xyW99QdD+2iw4zRToonwEFY30o=", "dev": true, "requires": { "mime-types": "~2.0.4", "negotiator": "0.4.9" }, "dependencies": { "mime-db": { "version": "1.12.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.12.0.tgz", "integrity": "sha1-PQxjGA9FjrENMlqqN9fFiuMS6dc=", "dev": true }, "mime-types": { "version": "2.0.14", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.14.tgz", "integrity": "sha1-MQ4VnbI+B3+Lsit0jav6SVcUCqY=", "dev": true, "requires": { "mime-db": "~1.12.0" } } } }, "after": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/after/-/after-0.8.1.tgz", "integrity": "sha1-q11PuIP1loFtNRX495HAr0ht1ic=", "dev": true }, "agent-base": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-2.1.1.tgz", "integrity": "sha1-1t4Q1a9hMtW9aSQn1G/FOFOQlMc=", "dev": true, "requires": { "extend": "~3.0.0", "semver": "~5.0.1" }, "dependencies": { "semver": { "version": "5.0.3", "resolved": "https://registry.npmjs.org/semver/-/semver-5.0.3.tgz", "integrity": "sha1-d0Zt5YnNXTyV8TiqeLxWmjy10no=", "dev": true } } }, "ajv": { "version": "4.11.8", "resolved": "https://registry.npmjs.org/ajv/-/ajv-4.11.8.tgz", "integrity": "sha1-gv+wKynmYq5TvcIK8VlHcGc5xTY=", "dev": true, "requires": { "co": "^4.6.0", "json-stable-stringify": "^1.0.1" } }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", "dev": true }, "ansi-styles": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", "dev": true }, "anymatch": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz", "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", "dev": true, "requires": { "micromatch": "^2.1.5", "normalize-path": "^2.0.0" } }, "argparse": { "version": "0.1.16", "resolved": "https://registry.npmjs.org/argparse/-/argparse-0.1.16.tgz", "integrity": "sha1-z9AeD7uj1srtBJ+9dY1A9lGW9Xw=", "dev": true, "requires": { "underscore": "~1.7.0", "underscore.string": "~2.4.0" }, "dependencies": { "underscore.string": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.4.0.tgz", "integrity": "sha1-jN2PusTi0uoefi6Al8QvRCKA+Fs=", "dev": true } } }, "arr-diff": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", "dev": true, "requires": { "arr-flatten": "^1.0.1" } }, "arr-flatten": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", "dev": true }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, "array-differ": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", "dev": true }, "array-find-index": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", "dev": true }, "array-slice": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", "dev": true }, "array-union": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", "dev": true, "requires": { "array-uniq": "^1.0.1" } }, "array-uniq": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", "dev": true }, "array-unique": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", "dev": true }, "arraybuffer.slice": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz", "integrity": "sha1-8zshWfBTKj8xB6JywMz70a0peco=", "dev": true }, "arrify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", "dev": true }, "asn1": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", - "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=", - "dev": true + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "requires": { + "safer-buffer": "~2.1.0" + } }, "assert-plus": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz", "integrity": "sha1-104bh+ev/A24qttwIfP+SBAasjQ=", "dev": true }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, "async": { "version": "0.1.22", "resolved": "https://registry.npmjs.org/async/-/async-0.1.22.tgz", "integrity": "sha1-D8GqoIig4+8Ovi2IMbqw3PiEUGE=", "dev": true }, "async-each": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", - "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.2.tgz", + "integrity": "sha512-6xrbvN0MOBKSJDdonmSSz2OwFSgxRaVtBDes26mj9KIGtDo+g9xosFRSC+i1gQh2oAN/tQ62AI/pGZGQjVOiRg==", "dev": true }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "dev": true }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, "aws-sign2": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz", "integrity": "sha1-FDQt0428yU0OW4fXY81jYSwOeU8=", "dev": true }, "aws4": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz", - "integrity": "sha1-g+9cqGCysy5KDe7e6MdxudtXRx4=", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", "dev": true }, "backo2": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz", "integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc=", "dev": true }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "dev": true }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + } + } + }, "base64-arraybuffer": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.2.tgz", "integrity": "sha1-R030qfLaJOBd8xWMOx2zw81GoVQ=", "dev": true }, "base64id": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/base64id/-/base64id-0.1.0.tgz", "integrity": "sha1-As4P3u4M709ACA4ec+g08LG/zj8=", "dev": true }, "bcrypt-pbkdf": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz", - "integrity": "sha1-Y7xdy2EzG5K8Bf1SiVPDNGKgb40=", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", "dev": true, - "optional": true, "requires": { "tweetnacl": "^0.14.3" } }, "benchmark": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz", "integrity": "sha1-CfPeMckWQl1JjMLuVloOvzwqVik=", "dev": true, "requires": { "lodash": "^4.17.4", "platform": "^1.3.3" } }, "better-assert": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz", "integrity": "sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI=", "dev": true, "requires": { "callsite": "1.0.0" } }, + "big-integer": { + "version": "1.6.43", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.43.tgz", + "integrity": "sha512-9dULc9jsKmXl0Aeunug8wbF+58n+hQoFjqClN7WeZwGLh0XJUWyJJ9Ee+Ep+Ql/J9fRsTVaeThp8MhiCCrY0Jg==", + "dev": true + }, "binary": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", "integrity": "sha1-n2BVO8XOjDOG87VTz/R0Yq3sqnk=", "dev": true, "requires": { "buffers": "~0.1.1", "chainsaw": "~0.1.0" } }, "binary-extensions": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.10.0.tgz", - "integrity": "sha1-muuabF6IY4qtFx4Wf1kAq+JINdA=", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz", + "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", "dev": true }, "blob": { "version": "0.0.4", "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.4.tgz", "integrity": "sha1-vPEwUspURj8w+fx+lbmkdjCpSSE=", "dev": true }, "bluebird": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz", - "integrity": "sha1-eRQg1/VR7qKJdFOop3ZT+WYG1nw=", + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.4.tgz", + "integrity": "sha512-FG+nFEZChJrbQ9tIccIfZJBz3J7mLrAhxakAbnrJWn8d7aKOC+LWifa0G+p4ZqKp4y13T7juYvdhq9NzKdsrjw==", "dev": true }, "body-parser": { "version": "1.14.2", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.14.2.tgz", "integrity": "sha1-EBXLH+LEQ4WCWVgdtTMy+NDPUPk=", "dev": true, "requires": { "bytes": "2.2.0", "content-type": "~1.0.1", "debug": "~2.2.0", "depd": "~1.1.0", "http-errors": "~1.3.1", "iconv-lite": "0.4.13", "on-finished": "~2.3.0", "qs": "5.2.0", "raw-body": "~2.1.5", "type-is": "~1.6.10" }, "dependencies": { + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, "iconv-lite": { "version": "0.4.13", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz", "integrity": "sha1-H4irpKsLFQjoMSrMOTRfNumS4vI=", "dev": true }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + }, "qs": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/qs/-/qs-5.2.0.tgz", "integrity": "sha1-qfMRQq9GjLcrJbMBNrokVoNJFr4=", "dev": true } } }, "boom": { "version": "2.10.1", "resolved": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", "integrity": "sha1-OciRjO/1eZ+D+UkqhI9iWt0Mdm8=", "dev": true, "requires": { "hoek": "2.x.x" } }, "brace-expansion": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", - "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "braces": { "version": "1.8.5", "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", "dev": true, "requires": { "expand-range": "^1.8.1", "preserve": "^0.2.0", "repeat-element": "^1.1.2" } }, "browserify-zlib": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.1.4.tgz", "integrity": "sha1-uzX4pRn2AOD6a4SFJByXnQFB+y0=", "dev": true, "requires": { "pako": "~0.2.0" } }, "browserstack": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/browserstack/-/browserstack-1.5.0.tgz", "integrity": "sha1-tWVCWtYu1ywQgqHrl51TE8fUdU8=", "dev": true, "requires": { "https-proxy-agent": "1.0.0" } }, "browserstacktunnel-wrapper": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/browserstacktunnel-wrapper/-/browserstacktunnel-wrapper-2.0.1.tgz", - "integrity": "sha1-/+GRDW45/oZhgYPoJmkAQa9T7a4=", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/browserstacktunnel-wrapper/-/browserstacktunnel-wrapper-2.0.4.tgz", + "integrity": "sha512-GCV599FUUxNOCFl3WgPnfc5dcqq9XTmMXoxWpqkvmk0R9TOIoqmjENNU6LY6DtgIL6WfBVbg/jmWtnM5K6UYSg==", + "dev": true, + "requires": { + "https-proxy-agent": "^2.2.1", + "unzipper": "^0.9.3" + }, + "dependencies": { + "agent-base": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.2.1.tgz", + "integrity": "sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg==", + "dev": true, + "requires": { + "es6-promisify": "^5.0.0" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "https-proxy-agent": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz", + "integrity": "sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ==", + "dev": true, + "requires": { + "agent-base": "^4.1.0", + "debug": "^3.1.0" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + } + } + }, + "buffer-alloc": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", + "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==", "dev": true, "requires": { - "https-proxy-agent": "^1.0.0", - "unzip": "~0.1.9" + "buffer-alloc-unsafe": "^1.1.0", + "buffer-fill": "^1.0.0" } }, + "buffer-alloc-unsafe": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz", + "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==", + "dev": true + }, + "buffer-fill": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", + "integrity": "sha1-+PeLdniYiO858gXNY39o5wISKyw=", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "buffer-indexof-polyfill": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.1.tgz", + "integrity": "sha1-qfuAbOgUXVQoUQznLyeLs2OmOL8=", + "dev": true + }, "buffers": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", "integrity": "sha1-skV5w77U1tOWru5tmorn9Ugqt7s=", "dev": true }, - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - }, "bytes": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-2.2.0.tgz", "integrity": "sha1-/TVGSkA/b5EXwt42Cez/nK4ABYg=", "dev": true }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, "callsite": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", "integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA=", "dev": true }, "camelcase": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", "dev": true }, "camelcase-keys": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "dev": true, "requires": { "camelcase": "^2.0.0", "map-obj": "^1.0.0" } }, "caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", "dev": true }, "chainsaw": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", "integrity": "sha1-XqtQsor+WAdNDVgpE4iCi15fvJg=", "dev": true, "requires": { "traverse": ">=0.3.0 <0.4" } }, "chalk": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "dev": true, "requires": { "ansi-styles": "^2.2.1", "escape-string-regexp": "^1.0.2", "has-ansi": "^2.0.0", "strip-ansi": "^3.0.0", "supports-color": "^2.0.0" } }, "chokidar": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", "dev": true, "requires": { "anymatch": "^1.3.0", "async-each": "^1.0.0", "fsevents": "^1.0.0", "glob-parent": "^2.0.0", "inherits": "^2.0.1", "is-binary-path": "^1.0.0", "is-glob": "^2.0.0", "path-is-absolute": "^1.0.0", "readdirp": "^2.0.0" } }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, "cli": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", "integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=", "dev": true, "requires": { "exit": "0.1.2", "glob": "^7.1.1" }, "dependencies": { "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } } } }, "co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", "dev": true }, "coffee-script": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/coffee-script/-/coffee-script-1.3.3.tgz", "integrity": "sha1-FQ1rTLUiiUNp7+1qIQHCC8f0pPQ=", "dev": true }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, "colors": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/colors/-/colors-0.6.2.tgz", "integrity": "sha1-JCP+ZnisDF2uiFLl0OW+CMmXq8w=", "dev": true }, "combine-lists": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/combine-lists/-/combine-lists-1.0.1.tgz", "integrity": "sha1-RYwH4J4NkA/Ci3Cj/sLazR0st/Y=", "dev": true, "requires": { "lodash": "^4.5.0" } }, "combined-stream": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", - "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", "dev": true, "requires": { "delayed-stream": "~1.0.0" } }, "commander": { "version": "2.11.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.11.0.tgz", "integrity": "sha512-b0553uYA5YAEGgyYIGYROzKQ7X5RAqedkfjiZxwi0kL1g3bOaBNNZfYkzt/CL0umgD5wc9Jec2FbB98CjkMRvQ==", "dev": true }, "commitplease": { "version": "2.7.10", "resolved": "https://registry.npmjs.org/commitplease/-/commitplease-2.7.10.tgz", "integrity": "sha1-Epr1q7NltG8l5lICDF0VSMlH8WM=", "dev": true, "requires": { "chalk": "^1.1.1", "git-tools": "^0.2.1", "ini": "^1.3.4", "object-assign": "^4.1.0", "semver": "^5.1.0" } }, "component-bind": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz", "integrity": "sha1-AMYIq33Nk4l8AAllGx06jh5zu9E=", "dev": true }, "component-emitter": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", - "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", "dev": true }, "component-inherit": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz", "integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM=", "dev": true }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, "concat-stream": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.0.tgz", - "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", "dev": true, "requires": { + "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^2.2.2", "typedarray": "^0.0.6" }, "dependencies": { "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", - "process-nextick-args": "~1.0.6", + "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", - "string_decoder": "~1.0.3", + "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "requires": { "safe-buffer": "~5.1.0" } } } }, "connect": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/connect/-/connect-3.6.3.tgz", - "integrity": "sha512-GLSZqgjVxPvGYVD/2vz//gS201MEXk4b7t3nHV6OVnTdDNWi/Gm7Rpxs/ybvljPWvULys/wrzIV3jB3YvEc3nQ==", + "version": "3.6.6", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.6.6.tgz", + "integrity": "sha1-Ce/2xVr3I24TcTWnJXSFi2eG9SQ=", "dev": true, "requires": { - "debug": "2.6.8", - "finalhandler": "1.0.4", - "parseurl": "~1.3.1", - "utils-merge": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.8", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.8.tgz", - "integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } + "debug": "2.6.9", + "finalhandler": "1.1.0", + "parseurl": "~1.3.2", + "utils-merge": "1.0.1" } }, "console-browserify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", "dev": true, "requires": { "date-now": "^0.1.4" } }, "content-type": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.2.tgz", - "integrity": "sha1-t9ETrueo3Se9IRM8TcJSnfFyHu0=", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, "core-js": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.0.tgz", - "integrity": "sha1-VpwFCRi+ZIazg3VSAorgRmtxcIY=", + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.5.tgz", + "integrity": "sha512-klh/kDpwX8hryYL14M9w/xei6vrv6sE8gTHDG7/T/+SEovB/G4ejwcfE/CBzO6Edsu+OETZMZ3wcX/EjUkrl5A==", "dev": true }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true }, "crc32": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/crc32/-/crc32-0.2.2.tgz", "integrity": "sha1-etIg1v/c0Rn5/BJ6d3LKzqOQpLo=", "dev": true }, "cryptiles": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.5.tgz", "integrity": "sha1-O9/s3GCBR8HGcgL6KR59ylnqo7g=", "dev": true, "requires": { "boom": "2.x.x" } }, "currently-unhandled": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", "dev": true, "requires": { "array-find-index": "^1.0.1" } }, "custom-event": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=", "dev": true }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", "dev": true, "requires": { "assert-plus": "^1.0.0" }, "dependencies": { "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true } } }, "date-now": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", "dev": true }, "dateformat": { "version": "1.0.2-1.2.3", "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.2-1.2.3.tgz", "integrity": "sha1-sCIMAt6YYXQztyhRz0fePfLNvuk=", "dev": true }, "debug": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", - "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { - "ms": "0.7.1" + "ms": "2.0.0" } }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + } + } + }, "deflate-js": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/deflate-js/-/deflate-js-0.2.3.tgz", "integrity": "sha1-+Fq7WOvFFRowYUdHPVfD5PfkQms=", "dev": true }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", "dev": true }, "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", "dev": true }, "di": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", "dev": true }, "dom-serialize": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", "dev": true, "requires": { "custom-event": "~1.0.0", "ent": "~2.2.0", "extend": "^3.0.0", "void-elements": "^2.0.0" } }, "dom-serializer": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", - "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", + "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", "dev": true, "requires": { - "domelementtype": "~1.1.1", - "entities": "~1.1.1" + "domelementtype": "^1.3.0", + "entities": "^1.1.1" }, "dependencies": { - "domelementtype": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", - "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=", - "dev": true - }, "entities": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", - "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", + "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==", "dev": true } } }, "domelementtype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", - "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", + "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", "dev": true }, "domhandler": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz", "integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=", "dev": true, "requires": { "domelementtype": "1" } }, "domutils": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", "dev": true, "requires": { "dom-serializer": "0", "domelementtype": "1" } }, + "duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha1-ixLauHjA1p4+eJEFFmKjL8a93ME=", + "dev": true, + "requires": { + "readable-stream": "^2.0.2" + }, + "dependencies": { + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, "ecc-jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", - "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", "dev": true, - "optional": true, "requires": { - "jsbn": "~0.1.0" + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" } }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", "dev": true }, "encodeurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.1.tgz", - "integrity": "sha1-eePVhlU0aQn+bw9Fpd5oEDspTSA=", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", "dev": true }, "engine.io": { "version": "1.6.10", "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-1.6.10.tgz", "integrity": "sha1-+H2E4b0h0aLsf43u8MYgVKzfsno=", "dev": true, "requires": { "accepts": "1.1.4", "base64id": "0.1.0", "debug": "2.2.0", "engine.io-parser": "1.2.4", "ws": "1.0.1" + }, + "dependencies": { + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + } } }, "engine.io-client": { "version": "1.6.9", "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-1.6.9.tgz", "integrity": "sha1-HWrUgEilCDyVCWlDsp0279shJAE=", "dev": true, "requires": { "component-emitter": "1.1.2", "component-inherit": "0.0.3", "debug": "2.2.0", "engine.io-parser": "1.2.4", "has-cors": "1.1.0", "indexof": "0.0.1", "parsejson": "0.0.1", "parseqs": "0.0.2", "parseuri": "0.0.4", "ws": "1.0.1", "xmlhttprequest-ssl": "1.5.1", "yeast": "0.1.2" - } - }, - "engine.io-parser": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-1.2.4.tgz", + }, + "dependencies": { + "component-emitter": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", + "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", + "dev": true + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + } + } + }, + "engine.io-parser": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-1.2.4.tgz", "integrity": "sha1-4Il7C/FOeS1M0qWVBVORnFaUjEI=", "dev": true, "requires": { "after": "0.8.1", "arraybuffer.slice": "0.0.6", "base64-arraybuffer": "0.1.2", "blob": "0.0.4", "has-binary": "0.1.6", "utf8": "2.1.0" }, "dependencies": { "has-binary": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/has-binary/-/has-binary-0.1.6.tgz", "integrity": "sha1-JTJvOc+k9hath4eJTjryz7x7bhA=", "dev": true, "requires": { "isarray": "0.0.1" } } } }, "ent": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", "dev": true }, "entities": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=", "dev": true }, "error-ex": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.1.tgz", - "integrity": "sha1-+FWobOYa3E6GIcPNoh56dhLDqNw=", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "dev": true, "requires": { "is-arrayish": "^0.2.1" } }, "es6-promise": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.0.5.tgz", "integrity": "sha1-eILzCt3lskDM+n99eMVIMwlRrkI=", "dev": true }, + "es6-promisify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", + "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", + "dev": true, + "requires": { + "es6-promise": "^4.0.3" + } + }, "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", "dev": true }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "esprima": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/esprima/-/esprima-1.0.4.tgz", "integrity": "sha1-n1V+CPw7TSbs6d00+Pv0drYlha0=", "dev": true }, "eventemitter2": { "version": "0.4.14", "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=", "dev": true }, "eventemitter3": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-1.2.0.tgz", - "integrity": "sha1-HIaZHYFq0eUEdQ5zh0Ik7PO+xQg=", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", + "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==", "dev": true }, "exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, "expand-braces": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/expand-braces/-/expand-braces-0.1.2.tgz", "integrity": "sha1-SIsdHSRRyz06axks/AMPRMWFX+o=", "dev": true, "requires": { "array-slice": "^0.2.3", "array-unique": "^0.2.1", "braces": "^0.1.2" }, "dependencies": { "braces": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/braces/-/braces-0.1.5.tgz", "integrity": "sha1-wIVxEIUpHYt1/ddOqw+FlygHEeY=", "dev": true, "requires": { "expand-range": "^0.1.0" } }, "expand-range": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-0.1.1.tgz", "integrity": "sha1-TLjtoJk8pW+k9B/ELzy7TMrf8EQ=", "dev": true, "requires": { "is-number": "^0.1.1", "repeat-string": "^0.2.2" } }, "is-number": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-number/-/is-number-0.1.1.tgz", "integrity": "sha1-aaevEWlj1HIG7JvZtIoUIW8eOAY=", "dev": true }, "repeat-string": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-0.2.2.tgz", "integrity": "sha1-x6jTI2BoNiBZp+RlH8aITosftK4=", "dev": true } } }, "expand-brackets": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", "dev": true, "requires": { "is-posix-bracket": "^0.1.0" } }, "expand-range": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", "dev": true, "requires": { "fill-range": "^2.1.0" } }, "extend": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", - "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, "extglob": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", "dev": true, "requires": { "is-extglob": "^1.0.0" } }, "extract-zip": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.5.tgz", - "integrity": "sha1-maBnNbbqIOqbcF13ms/8yHz/BEA=", + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz", + "integrity": "sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k=", "dev": true, "requires": { - "concat-stream": "1.6.0", - "debug": "2.2.0", - "mkdirp": "0.5.0", + "concat-stream": "1.6.2", + "debug": "2.6.9", + "mkdirp": "0.5.1", "yauzl": "2.4.1" } }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", "dev": true }, "faye-websocket": { "version": "0.10.0", "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", "dev": true, "requires": { "websocket-driver": ">=0.5.1" } }, "fd-slicer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", "dev": true, "requires": { "pend": "~1.2.0" } }, "figures": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5", "object-assign": "^4.1.0" } }, "filename-regex": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", "dev": true }, "fill-range": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", - "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz", + "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", "dev": true, "requires": { "is-number": "^2.1.0", "isobject": "^2.0.0", - "randomatic": "^1.1.3", + "randomatic": "^3.0.0", "repeat-element": "^1.1.2", "repeat-string": "^1.5.2" } }, "finalhandler": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.0.4.tgz", - "integrity": "sha512-16l/r8RgzlXKmFOhZpHBztvye+lAhC5SU7hXavnerC9UfZqZxxXl3BzL8MhffPT3kF61lj9Oav2LKEzh0ei7tg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", + "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", "dev": true, "requires": { - "debug": "2.6.8", + "debug": "2.6.9", "encodeurl": "~1.0.1", "escape-html": "~1.0.3", "on-finished": "~2.3.0", - "parseurl": "~1.3.1", + "parseurl": "~1.3.2", "statuses": "~1.3.1", "unpipe": "~1.0.0" }, "dependencies": { - "debug": { - "version": "2.6.8", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.8.tgz", - "integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", "dev": true } } }, "find-up": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { "path-exists": "^2.0.0", "pinkie-promise": "^2.0.0" } }, "findup-sync": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.1.3.tgz", "integrity": "sha1-fz56l7gjksZTvwZYm9hRkOk8NoM=", "dev": true, "requires": { "glob": "~3.2.9", "lodash": "~2.4.1" }, "dependencies": { "glob": { "version": "3.2.11", "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.11.tgz", "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", "dev": true, "requires": { "inherits": "2", "minimatch": "0.3" } }, "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true }, "minimatch": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz", "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } } } }, + "follow-redirects": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz", + "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==", + "dev": true, + "requires": { + "debug": "^3.2.6" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + } + } + }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", "dev": true }, "for-own": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", "dev": true, "requires": { "for-in": "^1.0.1" } }, "forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", "dev": true }, "form-data": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.1.4.tgz", "integrity": "sha1-M8GDrPGTJ27KqYFDpp6Uv+4XUNE=", "dev": true, "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.5", "mime-types": "^2.1.12" } }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, "fs-access": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fs-access/-/fs-access-1.0.1.tgz", "integrity": "sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o=", "dev": true, "requires": { "null-check": "^1.0.0" } }, "fs-extra": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-1.0.0.tgz", "integrity": "sha1-zTzl9+fLYUWIP8rjGR6Yd/hYeVA=", "dev": true, "requires": { "graceful-fs": "^4.1.2", "jsonfile": "^2.1.0", "klaw": "^1.0.0" }, "dependencies": { "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true } } }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, "fsevents": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.1.2.tgz", - "integrity": "sha512-Sn44E5wQW4bTHXvQmvSHwqbuiXtduD6Rrjm2ZtUEGbyrig+nUH3t/QD4M4/ZXViY556TBpRgZkHLDx3JxPwxiw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.7.tgz", + "integrity": "sha512-Pxm6sI2MeBD7RdD12RYsqaP0nMiwx8eZBXCa6z2L+mRHm2DYrOYwihmhjpkdjUHwQhslWQjRpEgNq4XvBmaAuw==", "dev": true, "optional": true, "requires": { - "nan": "^2.3.0", - "node-pre-gyp": "^0.6.36" + "nan": "^2.9.2", + "node-pre-gyp": "^0.10.0" }, "dependencies": { "abbrev": { - "version": "1.1.0", + "version": "1.1.1", "bundled": true, "dev": true, "optional": true }, - "ajv": { - "version": "4.11.8", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "co": "^4.6.0", - "json-stable-stringify": "^1.0.1" - } - }, "ansi-regex": { "version": "2.1.1", "bundled": true, "dev": true }, "aproba": { - "version": "1.1.1", + "version": "1.2.0", "bundled": true, "dev": true, "optional": true }, "are-we-there-yet": { - "version": "1.1.4", + "version": "1.1.5", "bundled": true, "dev": true, "optional": true, "requires": { "delegates": "^1.0.0", "readable-stream": "^2.0.6" } }, - "asn1": { - "version": "0.2.3", - "bundled": true, - "dev": true, - "optional": true - }, - "assert-plus": { - "version": "0.2.0", - "bundled": true, - "dev": true, - "optional": true - }, - "asynckit": { - "version": "0.4.0", - "bundled": true, - "dev": true, - "optional": true - }, - "aws-sign2": { - "version": "0.6.0", - "bundled": true, - "dev": true, - "optional": true - }, - "aws4": { - "version": "1.6.0", - "bundled": true, - "dev": true, - "optional": true - }, "balanced-match": { - "version": "0.4.2", + "version": "1.0.0", "bundled": true, "dev": true }, - "bcrypt-pbkdf": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "tweetnacl": "^0.14.3" - } - }, - "block-stream": { - "version": "0.0.9", - "bundled": true, - "dev": true, - "requires": { - "inherits": "~2.0.0" - } - }, - "boom": { - "version": "2.10.1", - "bundled": true, - "dev": true, - "requires": { - "hoek": "2.x.x" - } - }, "brace-expansion": { - "version": "1.1.7", + "version": "1.1.11", "bundled": true, "dev": true, "requires": { - "balanced-match": "^0.4.1", + "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, - "buffer-shims": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "caseless": { - "version": "0.12.0", - "bundled": true, - "dev": true, - "optional": true - }, - "co": { - "version": "4.6.0", + "chownr": { + "version": "1.1.1", "bundled": true, "dev": true, "optional": true }, "code-point-at": { "version": "1.1.0", "bundled": true, "dev": true }, - "combined-stream": { - "version": "1.0.5", - "bundled": true, - "dev": true, - "requires": { - "delayed-stream": "~1.0.0" - } - }, "concat-map": { "version": "0.0.1", "bundled": true, "dev": true }, "console-control-strings": { "version": "1.1.0", "bundled": true, "dev": true }, "core-util-is": { "version": "1.0.2", "bundled": true, - "dev": true - }, - "cryptiles": { - "version": "2.0.5", - "bundled": true, "dev": true, - "optional": true, - "requires": { - "boom": "2.x.x" - } - }, - "dashdash": { - "version": "1.14.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "^1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } + "optional": true }, "debug": { - "version": "2.6.8", + "version": "2.6.9", "bundled": true, "dev": true, "optional": true, "requires": { "ms": "2.0.0" } }, "deep-extend": { - "version": "0.4.2", + "version": "0.6.0", "bundled": true, "dev": true, "optional": true }, - "delayed-stream": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, "delegates": { "version": "1.0.0", "bundled": true, "dev": true, "optional": true }, - "ecc-jsbn": { - "version": "0.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsbn": "~0.1.0" - } - }, - "extend": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "extsprintf": { - "version": "1.0.2", - "bundled": true, - "dev": true - }, - "forever-agent": { - "version": "0.6.1", + "detect-libc": { + "version": "1.0.3", "bundled": true, "dev": true, "optional": true }, - "form-data": { - "version": "2.1.4", + "fs-minipass": { + "version": "1.2.5", "bundled": true, "dev": true, "optional": true, "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.5", - "mime-types": "^2.1.12" + "minipass": "^2.2.1" } }, "fs.realpath": { "version": "1.0.0", "bundled": true, - "dev": true - }, - "fstream": { - "version": "1.0.11", - "bundled": true, - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "inherits": "~2.0.0", - "mkdirp": ">=0.5 0", - "rimraf": "2" - } - }, - "fstream-ignore": { - "version": "1.0.5", - "bundled": true, "dev": true, - "optional": true, - "requires": { - "fstream": "^1.0.0", - "inherits": "2", - "minimatch": "^3.0.0" - } + "optional": true }, "gauge": { "version": "2.7.4", "bundled": true, "dev": true, "optional": true, "requires": { "aproba": "^1.0.3", "console-control-strings": "^1.0.0", "has-unicode": "^2.0.0", "object-assign": "^4.1.0", "signal-exit": "^3.0.0", "string-width": "^1.0.1", "strip-ansi": "^3.0.1", "wide-align": "^1.1.0" } }, - "getpass": { - "version": "0.1.7", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "^1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, "glob": { - "version": "7.1.2", + "version": "7.1.3", "bundled": true, "dev": true, + "optional": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, - "graceful-fs": { - "version": "4.1.11", - "bundled": true, - "dev": true - }, - "har-schema": { - "version": "1.0.5", - "bundled": true, - "dev": true, - "optional": true - }, - "har-validator": { - "version": "4.2.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ajv": "^4.9.1", - "har-schema": "^1.0.5" - } - }, "has-unicode": { "version": "2.0.1", "bundled": true, "dev": true, "optional": true }, - "hawk": { - "version": "3.1.3", + "iconv-lite": { + "version": "0.4.24", "bundled": true, "dev": true, "optional": true, "requires": { - "boom": "2.x.x", - "cryptiles": "2.x.x", - "hoek": "2.x.x", - "sntp": "1.x.x" + "safer-buffer": ">= 2.1.2 < 3" } }, - "hoek": { - "version": "2.16.3", - "bundled": true, - "dev": true - }, - "http-signature": { - "version": "1.1.1", + "ignore-walk": { + "version": "3.0.1", "bundled": true, "dev": true, "optional": true, "requires": { - "assert-plus": "^0.2.0", - "jsprim": "^1.2.2", - "sshpk": "^1.7.0" + "minimatch": "^3.0.4" } }, "inflight": { "version": "1.0.6", "bundled": true, "dev": true, + "optional": true, "requires": { "once": "^1.3.0", "wrappy": "1" } }, "inherits": { "version": "2.0.3", "bundled": true, "dev": true }, "ini": { - "version": "1.3.4", + "version": "1.3.5", "bundled": true, "dev": true, "optional": true }, "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, "dev": true, "requires": { "number-is-nan": "^1.0.0" } }, - "is-typedarray": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, "isarray": { "version": "1.0.0", "bundled": true, - "dev": true - }, - "isstream": { - "version": "0.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "jodid25519": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsbn": "~0.1.0" - } - }, - "jsbn": { - "version": "0.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "json-schema": { - "version": "0.2.3", - "bundled": true, - "dev": true, - "optional": true - }, - "json-stable-stringify": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsonify": "~0.0.0" - } - }, - "json-stringify-safe": { - "version": "5.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "jsonify": { - "version": "0.0.0", - "bundled": true, "dev": true, "optional": true }, - "jsprim": { - "version": "1.4.0", + "minimatch": { + "version": "3.0.4", "bundled": true, "dev": true, - "optional": true, "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.0.2", - "json-schema": "0.2.3", - "verror": "1.3.6" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } + "brace-expansion": "^1.1.7" } }, - "mime-db": { - "version": "1.27.0", + "minimist": { + "version": "0.0.8", "bundled": true, "dev": true }, - "mime-types": { - "version": "2.1.15", + "minipass": { + "version": "2.3.5", "bundled": true, "dev": true, "requires": { - "mime-db": "~1.27.0" + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" } }, - "minimatch": { - "version": "3.0.4", + "minizlib": { + "version": "1.2.1", "bundled": true, "dev": true, + "optional": true, "requires": { - "brace-expansion": "^1.1.7" + "minipass": "^2.2.1" } }, - "minimist": { - "version": "0.0.8", - "bundled": true, - "dev": true - }, "mkdirp": { "version": "0.5.1", "bundled": true, "dev": true, "requires": { "minimist": "0.0.8" } }, "ms": { "version": "2.0.0", "bundled": true, "dev": true, "optional": true }, + "needle": { + "version": "2.2.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "debug": "^2.1.2", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, "node-pre-gyp": { - "version": "0.6.36", + "version": "0.10.3", "bundled": true, "dev": true, "optional": true, "requires": { + "detect-libc": "^1.0.2", "mkdirp": "^0.5.1", + "needle": "^2.2.1", "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", "npmlog": "^4.0.2", - "rc": "^1.1.7", - "request": "^2.81.0", + "rc": "^1.2.7", "rimraf": "^2.6.1", "semver": "^5.3.0", - "tar": "^2.2.1", - "tar-pack": "^3.4.0" + "tar": "^4" } }, "nopt": { "version": "4.0.1", "bundled": true, "dev": true, "optional": true, "requires": { "abbrev": "1", "osenv": "^0.1.4" } }, + "npm-bundled": { + "version": "1.0.5", + "bundled": true, + "dev": true, + "optional": true + }, + "npm-packlist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, "npmlog": { - "version": "4.1.0", + "version": "4.1.2", "bundled": true, "dev": true, "optional": true, "requires": { "are-we-there-yet": "~1.1.2", "console-control-strings": "~1.1.0", "gauge": "~2.7.3", "set-blocking": "~2.0.0" } }, "number-is-nan": { "version": "1.0.1", "bundled": true, "dev": true }, - "oauth-sign": { - "version": "0.8.2", - "bundled": true, - "dev": true, - "optional": true - }, "object-assign": { "version": "4.1.1", "bundled": true, "dev": true, "optional": true }, "once": { "version": "1.4.0", "bundled": true, "dev": true, "requires": { "wrappy": "1" } }, "os-homedir": { "version": "1.0.2", "bundled": true, "dev": true, "optional": true }, "os-tmpdir": { "version": "1.0.2", "bundled": true, "dev": true, "optional": true }, "osenv": { - "version": "0.1.4", + "version": "0.1.5", "bundled": true, "dev": true, "optional": true, "requires": { "os-homedir": "^1.0.0", "os-tmpdir": "^1.0.0" } }, "path-is-absolute": { "version": "1.0.1", "bundled": true, - "dev": true - }, - "performance-now": { - "version": "0.2.0", - "bundled": true, "dev": true, "optional": true }, "process-nextick-args": { - "version": "1.0.7", - "bundled": true, - "dev": true - }, - "punycode": { - "version": "1.4.1", - "bundled": true, - "dev": true, - "optional": true - }, - "qs": { - "version": "6.4.0", + "version": "2.0.0", "bundled": true, "dev": true, "optional": true }, "rc": { - "version": "1.2.1", + "version": "1.2.8", "bundled": true, "dev": true, "optional": true, "requires": { - "deep-extend": "~0.4.0", + "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "dependencies": { "minimist": { "version": "1.2.0", "bundled": true, "dev": true, "optional": true } } }, "readable-stream": { - "version": "2.2.9", + "version": "2.3.6", "bundled": true, "dev": true, + "optional": true, "requires": { - "buffer-shims": "~1.0.0", "core-util-is": "~1.0.0", - "inherits": "~2.0.1", + "inherits": "~2.0.3", "isarray": "~1.0.0", - "process-nextick-args": "~1.0.6", - "string_decoder": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, - "request": { - "version": "2.81.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "aws-sign2": "~0.6.0", - "aws4": "^1.2.1", - "caseless": "~0.12.0", - "combined-stream": "~1.0.5", - "extend": "~3.0.0", - "forever-agent": "~0.6.1", - "form-data": "~2.1.1", - "har-validator": "~4.2.1", - "hawk": "~3.1.3", - "http-signature": "~1.1.0", - "is-typedarray": "~1.0.0", - "isstream": "~0.1.2", - "json-stringify-safe": "~5.0.1", - "mime-types": "~2.1.7", - "oauth-sign": "~0.8.1", - "performance-now": "^0.2.0", - "qs": "~6.4.0", - "safe-buffer": "^5.0.1", - "stringstream": "~0.0.4", - "tough-cookie": "~2.3.0", - "tunnel-agent": "^0.6.0", - "uuid": "^3.0.0" - } - }, "rimraf": { - "version": "2.6.1", - "bundled": true, - "dev": true, - "requires": { - "glob": "^7.0.5" - } - }, - "safe-buffer": { - "version": "5.0.1", - "bundled": true, - "dev": true - }, - "semver": { - "version": "5.3.0", - "bundled": true, - "dev": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "sntp": { - "version": "1.0.9", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "hoek": "2.x.x" - } - }, - "sshpk": { - "version": "1.13.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "asn1": "~0.2.3", - "assert-plus": "^1.0.0", - "bcrypt-pbkdf": "^1.0.0", - "dashdash": "^1.12.0", - "ecc-jsbn": "~0.1.1", - "getpass": "^0.1.1", - "jodid25519": "^1.0.0", - "jsbn": "~0.1.0", - "tweetnacl": "~0.14.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "string-width": { - "version": "1.0.2", + "version": "2.6.3", "bundled": true, "dev": true, + "optional": true, "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" + "glob": "^7.1.3" } }, - "string_decoder": { - "version": "1.0.1", + "safe-buffer": { + "version": "5.1.2", + "bundled": true, + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", "bundled": true, "dev": true, - "requires": { - "safe-buffer": "^5.0.1" - } + "optional": true }, - "stringstream": { - "version": "0.0.5", + "sax": { + "version": "1.2.4", "bundled": true, "dev": true, "optional": true }, - "strip-ansi": { - "version": "3.0.1", + "semver": { + "version": "5.6.0", "bundled": true, "dev": true, - "requires": { - "ansi-regex": "^2.0.0" - } + "optional": true }, - "strip-json-comments": { - "version": "2.0.1", + "set-blocking": { + "version": "2.0.0", "bundled": true, "dev": true, "optional": true }, - "tar": { - "version": "2.2.1", + "signal-exit": { + "version": "3.0.2", "bundled": true, "dev": true, - "requires": { - "block-stream": "*", - "fstream": "^1.0.2", - "inherits": "2" - } + "optional": true }, - "tar-pack": { - "version": "3.4.0", + "string-width": { + "version": "1.0.2", "bundled": true, "dev": true, - "optional": true, "requires": { - "debug": "^2.2.0", - "fstream": "^1.0.10", - "fstream-ignore": "^1.0.5", - "once": "^1.3.3", - "readable-stream": "^2.1.4", - "rimraf": "^2.5.1", - "tar": "^2.2.1", - "uid-number": "^0.0.6" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, - "tough-cookie": { - "version": "2.3.2", + "string_decoder": { + "version": "1.1.1", "bundled": true, "dev": true, "optional": true, "requires": { - "punycode": "^1.4.1" + "safe-buffer": "~5.1.0" } }, - "tunnel-agent": { - "version": "0.6.0", + "strip-ansi": { + "version": "3.0.1", "bundled": true, "dev": true, - "optional": true, "requires": { - "safe-buffer": "^5.0.1" + "ansi-regex": "^2.0.0" } }, - "tweetnacl": { - "version": "0.14.5", + "strip-json-comments": { + "version": "2.0.1", "bundled": true, "dev": true, "optional": true }, - "uid-number": { - "version": "0.0.6", + "tar": { + "version": "4.4.8", "bundled": true, "dev": true, - "optional": true + "optional": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.3.4", + "minizlib": "^1.1.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.2" + } }, "util-deprecate": { "version": "1.0.2", "bundled": true, - "dev": true - }, - "uuid": { - "version": "3.0.1", - "bundled": true, "dev": true, "optional": true }, - "verror": { - "version": "1.3.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "extsprintf": "1.0.2" - } - }, "wide-align": { - "version": "1.1.2", + "version": "1.1.3", "bundled": true, "dev": true, "optional": true, "requires": { - "string-width": "^1.0.2" + "string-width": "^1.0.2 || 2" } }, "wrappy": { "version": "1.0.2", "bundled": true, "dev": true + }, + "yallist": { + "version": "3.0.3", + "bundled": true, + "dev": true } } }, "fstream": { - "version": "0.1.31", - "resolved": "https://registry.npmjs.org/fstream/-/fstream-0.1.31.tgz", - "integrity": "sha1-czfwWPu7vvqMn1YaKMqwhJICyYg=", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", + "integrity": "sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=", "dev": true, "requires": { - "graceful-fs": "~3.0.2", + "graceful-fs": "^4.1.2", "inherits": "~2.0.0", - "mkdirp": "0.5", + "mkdirp": ">=0.5 0", "rimraf": "2" }, "dependencies": { "graceful-fs": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.11.tgz", - "integrity": "sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg=", - "dev": true, - "requires": { - "natives": "^1.1.0" - } + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", + "dev": true } } }, "gaze": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.2.tgz", - "integrity": "sha1-hHIkZ3rbiHDWeSV+0ziP22HkAQU=", + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.3.tgz", + "integrity": "sha512-BRdNm8hbWzFzWHERTrejLqwHDfS4GibPoq5wjTPIoJHoBtKGPg3xAFfxmM+9ztbXelxcf2hwQcaz1PtmFeue8g==", "dev": true, "requires": { "globule": "^1.0.0" } }, "get-stdin": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", "dev": true }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, "getobject": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/getobject/-/getobject-0.1.0.tgz", "integrity": "sha1-BHpEl4n6Fg0Bj1SG7ZEyC27HiFw=", "dev": true }, "getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", "dev": true, "requires": { "assert-plus": "^1.0.0" }, "dependencies": { "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true } } }, "git-tools": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/git-tools/-/git-tools-0.2.1.tgz", "integrity": "sha1-bhhGrywOkatZJYtI+bU8EnmzsnM=", "dev": true, "requires": { "spawnback": "~1.0.0" } }, "glob": { "version": "3.1.21", "resolved": "https://registry.npmjs.org/glob/-/glob-3.1.21.tgz", "integrity": "sha1-0p4KBV3qUTj00H7UDomC6DwgZs0=", "dev": true, "requires": { "graceful-fs": "~1.2.0", "inherits": "1", "minimatch": "~0.2.11" }, "dependencies": { "inherits": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/inherits/-/inherits-1.0.2.tgz", "integrity": "sha1-ykMJ2t7mtUzAuNJH6NfHoJdb3Js=", "dev": true } } }, "glob-base": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", "dev": true, "requires": { "glob-parent": "^2.0.0", "is-glob": "^2.0.0" } }, "glob-parent": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", "dev": true, "requires": { "is-glob": "^2.0.0" } }, "globule": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/globule/-/globule-1.2.0.tgz", - "integrity": "sha1-HcScaCLdnoovoAuiopUAboZkvQk=", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/globule/-/globule-1.2.1.tgz", + "integrity": "sha512-g7QtgWF4uYSL5/dn71WxubOrS7JVGCnFPEnoeChJmBnyR9Mw8nGoEwOgJL/RC2Te0WhbsEUCejfH8SZNJ+adYQ==", "dev": true, "requires": { "glob": "~7.1.1", - "lodash": "~4.17.4", + "lodash": "~4.17.10", "minimatch": "~3.0.2" }, "dependencies": { "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } } } }, "graceful-fs": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.3.tgz", "integrity": "sha1-FaSAaldUfLLS2/J/QuiajDRRs2Q=", "dev": true }, "grunt": { "version": "0.4.5", "resolved": "https://registry.npmjs.org/grunt/-/grunt-0.4.5.tgz", "integrity": "sha1-VpN81RlDJK3/bSB2MYMqnWuk5/A=", "dev": true, "requires": { "async": "~0.1.22", "coffee-script": "~1.3.3", "colors": "~0.6.2", "dateformat": "1.0.2-1.2.3", "eventemitter2": "~0.4.13", "exit": "~0.1.1", "findup-sync": "~0.1.2", "getobject": "~0.1.0", "glob": "~3.1.21", "grunt-legacy-log": "~0.1.0", "grunt-legacy-util": "~0.2.0", "hooker": "~0.2.3", "iconv-lite": "~0.2.11", "js-yaml": "~2.0.5", "lodash": "~0.9.2", "minimatch": "~0.2.12", "nopt": "~1.0.10", "rimraf": "~2.2.8", "underscore.string": "~2.2.1", "which": "~1.0.5" }, "dependencies": { "lodash": { "version": "0.9.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-0.9.2.tgz", "integrity": "sha1-jzSZxSRdNG1oLlsNO0B2fgnxqSw=", "dev": true } } }, "grunt-cli": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/grunt-cli/-/grunt-cli-0.1.13.tgz", "integrity": "sha1-6evEBHYx9QEtkidww5N4EzytEPQ=", "dev": true, "requires": { "findup-sync": "~0.1.0", "nopt": "~1.0.10", "resolve": "~0.3.1" } }, "grunt-compare-size": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/grunt-compare-size/-/grunt-compare-size-0.4.2.tgz", "integrity": "sha1-0qvx082dOaFiA+EdI7cYtXV571E=", "dev": true, "requires": { "lodash": "^4.11.1" } }, "grunt-contrib-jshint": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/grunt-contrib-jshint/-/grunt-contrib-jshint-1.1.0.tgz", "integrity": "sha1-Np2QmyWTxA6L55lAshNAhQx5Oaw=", "dev": true, "requires": { "chalk": "^1.1.1", "hooker": "^0.2.3", "jshint": "~2.9.4" } }, "grunt-contrib-qunit": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/grunt-contrib-qunit/-/grunt-contrib-qunit-2.0.0.tgz", "integrity": "sha1-VKUbSyyE/uYsO34AFFySjR7Ct+w=", "dev": true, "requires": { "grunt-lib-phantomjs": "^1.0.0" } }, "grunt-contrib-uglify": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/grunt-contrib-uglify/-/grunt-contrib-uglify-3.0.1.tgz", "integrity": "sha1-/etfk4pMgEL46Grkb2NVTo6VEcs=", "dev": true, "requires": { "chalk": "^1.0.0", "maxmin": "^1.1.0", "uglify-js": "~3.0.4", "uri-path": "^1.0.0" } }, "grunt-contrib-watch": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/grunt-contrib-watch/-/grunt-contrib-watch-1.0.0.tgz", "integrity": "sha1-hKGnodar0m7VaEE0lscxM+mQAY8=", "dev": true, "requires": { "async": "^1.5.0", "gaze": "^1.0.0", "lodash": "^3.10.1", "tiny-lr": "^0.2.1" }, "dependencies": { "async": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", "dev": true }, "lodash": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", "dev": true } } }, "grunt-git-authors": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/grunt-git-authors/-/grunt-git-authors-3.2.0.tgz", "integrity": "sha1-D/WrbTxu/+CrIV1jNDRcD2v+FnI=", "dev": true, "requires": { "spawnback": "~1.0.0" } }, "grunt-jscs": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/grunt-jscs/-/grunt-jscs-0.6.2.tgz", "integrity": "sha1-DKgUl0wrTNioiXLV42RnsRRPfB8=", "dev": true, "requires": { "hooker": "~0.2.3", "jscs": "~1.5.9", "lodash": "~2.4.1", "vow": "~0.4.1" }, "dependencies": { "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true } } }, "grunt-jsonlint": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/grunt-jsonlint/-/grunt-jsonlint-1.1.0.tgz", "integrity": "sha1-ox7pckCu4/NDyiY8Rb1TIGMSfbI=", "dev": true, "requires": { "jsonlint": "1.6.2", "strip-json-comments": "^2.0.0" }, "dependencies": { "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", "dev": true } } }, "grunt-karma": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/grunt-karma/-/grunt-karma-2.0.0.tgz", "integrity": "sha1-dTWD0RXf3AVf5X5Y+W1rPH5hIRg=", "dev": true, "requires": { "lodash": "^3.10.1" }, "dependencies": { "lodash": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", "dev": true } } }, "grunt-legacy-log": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/grunt-legacy-log/-/grunt-legacy-log-0.1.3.tgz", "integrity": "sha1-7ClCboAwIa9ZAp+H0vnNczWgVTE=", "dev": true, "requires": { "colors": "~0.6.2", "grunt-legacy-log-utils": "~0.1.1", "hooker": "~0.2.3", "lodash": "~2.4.1", "underscore.string": "~2.3.3" }, "dependencies": { "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true }, "underscore.string": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.3.3.tgz", "integrity": "sha1-ccCL9rQosRM/N+ePo6Icgvcymw0=", "dev": true } } }, "grunt-legacy-log-utils": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/grunt-legacy-log-utils/-/grunt-legacy-log-utils-0.1.1.tgz", "integrity": "sha1-wHBrndkGThFvNvI/5OawSGcsD34=", "dev": true, "requires": { "colors": "~0.6.2", "lodash": "~2.4.1", "underscore.string": "~2.3.3" }, "dependencies": { "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true }, "underscore.string": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.3.3.tgz", "integrity": "sha1-ccCL9rQosRM/N+ePo6Icgvcymw0=", "dev": true } } }, "grunt-legacy-util": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/grunt-legacy-util/-/grunt-legacy-util-0.2.0.tgz", "integrity": "sha1-kzJIhNv343qf98Am3/RR2UqeVUs=", "dev": true, "requires": { "async": "~0.1.22", "exit": "~0.1.1", "getobject": "~0.1.0", "hooker": "~0.2.3", "lodash": "~0.9.2", "underscore.string": "~2.2.1", "which": "~1.0.5" }, "dependencies": { "lodash": { "version": "0.9.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-0.9.2.tgz", "integrity": "sha1-jzSZxSRdNG1oLlsNO0B2fgnxqSw=", "dev": true } } }, "grunt-lib-phantomjs": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/grunt-lib-phantomjs/-/grunt-lib-phantomjs-1.1.0.tgz", "integrity": "sha1-np7c3Z/S3UDgwYHJQ3HVcqpe6tI=", "dev": true, "requires": { "eventemitter2": "^0.4.9", "phantomjs-prebuilt": "^2.1.3", "rimraf": "^2.5.2", "semver": "^5.1.0", "temporary": "^0.0.8" }, "dependencies": { "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, "rimraf": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.1.tgz", - "integrity": "sha1-wjOOxkPfeht/5cVPqG9XQopV8z0=", + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", "dev": true, "requires": { - "glob": "^7.0.5" + "glob": "^7.1.3" } } } }, "grunt-npmcopy": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/grunt-npmcopy/-/grunt-npmcopy-0.1.0.tgz", "integrity": "sha1-pAnSXHv3eDA/a5GAVH1ngENMdX8=", "dev": true, "requires": { "glob": "^4.0.2", "lodash": "^2.4.1" }, "dependencies": { "glob": { "version": "4.5.3", "resolved": "https://registry.npmjs.org/glob/-/glob-4.5.3.tgz", "integrity": "sha1-xstz0yJsHv7wTePFbQEvAzd+4V8=", "dev": true, "requires": { "inflight": "^1.0.4", "inherits": "2", "minimatch": "^2.0.1", "once": "^1.3.0" } }, "lodash": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-2.4.2.tgz", "integrity": "sha1-+t2DS5aDBz2hebPq5tnA0VBT9z4=", "dev": true }, "minimatch": { "version": "2.0.10", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.10.tgz", "integrity": "sha1-jQh8OcazjAAbl/ynzm0OHoCvusc=", "dev": true, "requires": { "brace-expansion": "^1.0.0" } } } }, "gzip-js": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/gzip-js/-/gzip-js-0.3.2.tgz", "integrity": "sha1-IxF+/usozzhSSN7/Df+tiUg22Ws=", "dev": true, "requires": { "crc32": ">= 0.2.2", "deflate-js": ">= 0.2.2" } }, "gzip-size": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-1.0.0.tgz", "integrity": "sha1-Zs+LEBBHInuVus5uodoMF37Vwi8=", "dev": true, "requires": { "browserify-zlib": "^0.1.4", "concat-stream": "^1.4.1" } }, "har-schema": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-1.0.5.tgz", "integrity": "sha1-0mMTX0MwfALGAq/I/pWXDAFRNp4=", "dev": true }, "har-validator": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-4.2.1.tgz", "integrity": "sha1-M0gdDxu/9gDdID11gSpqX7oALio=", "dev": true, "requires": { "ajv": "^4.9.1", "har-schema": "^1.0.5" } }, "has-ansi": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", "dev": true, "requires": { "ansi-regex": "^2.0.0" } }, "has-binary": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/has-binary/-/has-binary-0.1.7.tgz", "integrity": "sha1-aOYesWIQyVRaClzOBqhzkS/h5ow=", "dev": true, "requires": { "isarray": "0.0.1" } }, "has-color": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/has-color/-/has-color-0.1.7.tgz", "integrity": "sha1-ZxRKUmDDT8PMpnfQQdr1L+e3iy8=", "dev": true }, "has-cors": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-cors/-/has-cors-1.1.0.tgz", "integrity": "sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk=", "dev": true }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, "hasha": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/hasha/-/hasha-2.2.0.tgz", "integrity": "sha1-eNfL/B5tZjA/55g3NlmEUXsvbuE=", "dev": true, "requires": { "is-stream": "^1.0.1", "pinkie-promise": "^2.0.0" } }, "hawk": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/hawk/-/hawk-3.1.3.tgz", "integrity": "sha1-B4REvXwWQLD+VA0sm3PVlnjo4cQ=", "dev": true, "requires": { "boom": "2.x.x", "cryptiles": "2.x.x", "hoek": "2.x.x", "sntp": "1.x.x" } }, "hoek": { "version": "2.16.3", "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz", "integrity": "sha1-ILt0A9POo5jpHcRxCo/xuCdKJe0=", "dev": true }, "hooker": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/hooker/-/hooker-0.2.3.tgz", "integrity": "sha1-uDT3I8xKJCqmWWNFnfbZhMXT2Vk=", "dev": true }, "hosted-git-info": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.5.0.tgz", - "integrity": "sha512-pNgbURSuab90KbTqvRPsseaTxOJCZBD0a7t+haSN33piP9cCM4l0CqdzAif2hUqm716UovKB2ROmiabGAKVXyg==", + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", "dev": true }, "htmlparser2": { "version": "3.8.3", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz", "integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=", "dev": true, "requires": { "domelementtype": "1", "domhandler": "2.3", "domutils": "1.5", "entities": "1.0", "readable-stream": "1.1" } }, "http-errors": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", "integrity": "sha1-GX4izevUGYWF6GlO9nhhl7ke2UI=", "dev": true, "requires": { "inherits": "~2.0.1", "statuses": "1" } }, + "http-parser-js": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.0.tgz", + "integrity": "sha512-cZdEF7r4gfRIq7ezX9J0T+kQmJNOub71dWbgAXVHDct80TKP4MCETtZQ31xyv38UwgzkWPYF/Xc0ge55dW9Z9w==", + "dev": true + }, "http-proxy": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.16.2.tgz", - "integrity": "sha1-Bt/ykpUr9k2+hHH6nfcwZtTzd0I=", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.17.0.tgz", + "integrity": "sha512-Taqn+3nNvYRfJ3bGvKfBSRwy1v6eePlm3oc/aWVxZp57DQr5Eq3xhKJi7Z4hZpS8PC3H4qI+Yly5EmFacGuA/g==", "dev": true, "requires": { - "eventemitter3": "1.x.x", - "requires-port": "1.x.x" + "eventemitter3": "^3.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" } }, "http-signature": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.1.1.tgz", "integrity": "sha1-33LiZwZs0Kxn+3at+OE0qPvPkb8=", "dev": true, "requires": { "assert-plus": "^0.2.0", "jsprim": "^1.2.2", "sshpk": "^1.7.0" } }, "https-proxy-agent": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-1.0.0.tgz", "integrity": "sha1-NffabEjOTdv6JkiRrFk+5f+GceY=", "dev": true, "requires": { "agent-base": "2", "debug": "2", "extend": "3" } }, "iconv-lite": { "version": "0.2.11", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.2.11.tgz", "integrity": "sha1-HOYKOleGSiktEyH/RgnKS7llrcg=", "dev": true }, "indent-string": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", "dev": true, "requires": { "repeating": "^2.0.0" } }, "indexof": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=", "dev": true }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { "once": "^1.3.0", "wrappy": "1" } }, "inherits": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true }, "ini": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", - "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", "dev": true }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + }, "is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, "is-binary-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", "dev": true, "requires": { "binary-extensions": "^1.0.0" } }, "is-buffer": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.5.tgz", - "integrity": "sha1-Hzsm72E7IUuIy8ojzGwB2Hlh7sw=", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", "dev": true }, - "is-builtin-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", - "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { - "builtin-modules": "^1.0.0" + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } } }, "is-dotfile": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", "dev": true }, "is-equal-shallow": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", "dev": true, "requires": { "is-primitive": "^2.0.0" } }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", "dev": true }, "is-extglob": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", "dev": true }, "is-finite": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", "dev": true, "requires": { "number-is-nan": "^1.0.0" } }, "is-glob": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", "dev": true, "requires": { "is-extglob": "^1.0.0" } }, "is-number": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", "dev": true, "requires": { "kind-of": "^3.0.2" } }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, "is-posix-bracket": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", "dev": true }, "is-primitive": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", "dev": true }, "is-stream": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", "dev": true }, "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", "dev": true }, "is-utf8": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", "dev": true }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", "dev": true }, "isbinaryfile": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.2.tgz", - "integrity": "sha1-Sj6XTsDLqQBNP8bN5yCeppNopiE=", - "dev": true + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.3.tgz", + "integrity": "sha512-8cJBL5tTd2OS0dM4jz07wQd5g0dCCqIhUxPIGtZfa5L6hWlvV5MHTITy/DBAsF+Oe2LS1X3krBUhNwaGUWpWxw==", + "dev": true, + "requires": { + "buffer-alloc": "^1.2.0" + } }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, "isobject": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", "dev": true, "requires": { "isarray": "1.0.0" }, "dependencies": { "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true } } }, "isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", "dev": true }, "jquery": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/jquery/-/jquery-1.9.1.tgz", "integrity": "sha1-5M1INfqu+63lNYV2E8D8P/KtrzQ=", "dev": true }, "js-yaml": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-2.0.5.tgz", "integrity": "sha1-olrmUJmZ6X3yeMZxnaEb0Gh3Q6g=", "dev": true, "requires": { "argparse": "~ 0.1.11", "esprima": "~ 1.0.2" } }, "jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", - "dev": true, - "optional": true + "dev": true }, "jscs": { "version": "1.5.9", "resolved": "https://registry.npmjs.org/jscs/-/jscs-1.5.9.tgz", "integrity": "sha1-3u2ibEuckNbaVkeuW6IQxctds9U=", "dev": true, "requires": { "colors": "~0.6.2", "commander": "~2.3.0", "esprima": "~1.2.2", "glob": "~4.0.0", "minimatch": "~0.4.0", "strip-json-comments": "~0.1.1", "supports-color": "~0.2.0", "vow": "~0.4.3", "vow-fs": "~0.3.1", "xmlbuilder": "~2.3.0" }, "dependencies": { "commander": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.3.0.tgz", "integrity": "sha1-/UMOiJgy7DU7ms0d4hfBHLPu+HM=", "dev": true }, "esprima": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/esprima/-/esprima-1.2.5.tgz", "integrity": "sha1-CZNQL+r2aBODJXVvMPmlH+7sEek=", "dev": true }, "glob": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/glob/-/glob-4.0.6.tgz", "integrity": "sha1-aVxQvdTi+1xdNwsJHziNNwfikac=", "dev": true, "requires": { "graceful-fs": "^3.0.2", "inherits": "2", "minimatch": "^1.0.0", "once": "^1.3.0" }, "dependencies": { "minimatch": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-1.0.0.tgz", "integrity": "sha1-4N0hILSeG3JM6NcUxSCCKpQ4V20=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } } } }, "graceful-fs": { "version": "3.0.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.11.tgz", "integrity": "sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg=", "dev": true, "requires": { "natives": "^1.1.0" } }, "minimatch": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.4.0.tgz", "integrity": "sha1-vSx9Bg0sjI/Xzefx8u0tWycP2xs=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } }, "strip-json-comments": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-0.1.3.tgz", "integrity": "sha1-Fkxk43Coo8wAyeAbU55WmCPw7lQ=", "dev": true }, "supports-color": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-0.2.0.tgz", "integrity": "sha1-2S3iaU6z9nMjlz1649i1W0wiGQo=", "dev": true } } }, "jshint": { - "version": "2.9.5", - "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.9.5.tgz", - "integrity": "sha1-HnJSkVzmgbQIJ+4UJIxG006apiw=", + "version": "2.9.7", + "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.9.7.tgz", + "integrity": "sha512-Q8XN38hGsVQhdlM+4gd1Xl7OB1VieSuCJf+fEJjpo59JH99bVJhXRXAh26qQ15wfdd1VPMuDWNeSWoNl53T4YA==", "dev": true, "requires": { "cli": "~1.0.0", "console-browserify": "1.1.x", "exit": "0.1.x", "htmlparser2": "3.8.x", - "lodash": "3.7.x", + "lodash": "~4.17.10", "minimatch": "~3.0.2", "shelljs": "0.3.x", "strip-json-comments": "1.0.x" }, "dependencies": { - "lodash": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.7.0.tgz", - "integrity": "sha1-Nni9irmVBXwHreg27S7wh9qBHUU=", - "dev": true - }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } } } }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", "dev": true }, "json-stable-stringify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz", "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", "dev": true, "requires": { "jsonify": "~0.0.0" } }, "json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", "dev": true }, "json3": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/json3/-/json3-3.2.6.tgz", "integrity": "sha1-9u/JPAagTemuxTBT3yVZuxniA4s=", "dev": true }, "jsonfile": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", "dev": true, "requires": { "graceful-fs": "^4.1.6" }, "dependencies": { "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true, "optional": true } } }, "jsonify": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz", "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=", "dev": true }, "jsonlint": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/jsonlint/-/jsonlint-1.6.2.tgz", "integrity": "sha1-VzcEUIX1XrRVxosf9OvAG9UOiDA=", "dev": true, "requires": { "JSV": ">= 4.0.x", "nomnom": ">= 1.5.x" } }, "jsprim": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", "dev": true, "requires": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", "json-schema": "0.2.3", "verror": "1.10.0" }, "dependencies": { "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true } } }, "karma": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/karma/-/karma-1.3.0.tgz", "integrity": "sha1-srlOj0mfrdAGnVT5rvSk1I7FzB8=", "dev": true, "requires": { "bluebird": "^3.3.0", "body-parser": "^1.12.4", "chokidar": "^1.4.1", "colors": "^1.1.0", "combine-lists": "^1.0.0", "connect": "^3.3.5", "core-js": "^2.2.0", "di": "^0.0.1", "dom-serialize": "^2.2.0", "expand-braces": "^0.1.1", "glob": "^7.0.3", "graceful-fs": "^4.1.2", "http-proxy": "^1.13.0", "isbinaryfile": "^3.0.0", "lodash": "^3.8.0", "log4js": "^0.6.31", "mime": "^1.3.4", "minimatch": "^3.0.0", "optimist": "^0.6.1", "qjobs": "^1.1.4", "range-parser": "^1.2.0", "rimraf": "^2.3.3", "socket.io": "1.4.7", "source-map": "^0.5.3", "tmp": "0.0.28", "useragent": "^2.1.9" }, "dependencies": { "colors": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", - "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.3.3.tgz", + "integrity": "sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg==", "dev": true }, "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true }, "lodash": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", "dev": true }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, "rimraf": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.1.tgz", - "integrity": "sha1-wjOOxkPfeht/5cVPqG9XQopV8z0=", + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", "dev": true, "requires": { - "glob": "^7.0.5" + "glob": "^7.1.3" } } } }, "karma-browserstack-launcher": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/karma-browserstack-launcher/-/karma-browserstack-launcher-1.3.0.tgz", "integrity": "sha512-LrPf5sU/GISkEElWyoy06J8x0c8BcOjjOwf61Wqu6M0aWQu0Eoqm9yh3xON64/ByST/CEr0GsWiREQ/EIEMd4Q==", "dev": true, "requires": { "browserstack": "1.5.0", "browserstacktunnel-wrapper": "~2.0.1", "q": "~1.5.0" } }, "karma-chrome-launcher": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-2.2.0.tgz", "integrity": "sha512-uf/ZVpAabDBPvdPdveyk1EPgbnloPvFFGgmRhYLTDH7gEB4nZdSBk8yTU47w1g/drLSx5uMOkjKk7IWKfWg/+w==", "dev": true, "requires": { "fs-access": "^1.0.0", "which": "^1.2.1" }, "dependencies": { "which": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", - "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", "dev": true, "requires": { "isexe": "^2.0.0" } } } }, "karma-firefox-launcher": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/karma-firefox-launcher/-/karma-firefox-launcher-1.0.1.tgz", "integrity": "sha1-zlj0fCATqIFW1VpdYTN8CZz1u1E=", "dev": true }, "karma-html2js-preprocessor": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/karma-html2js-preprocessor/-/karma-html2js-preprocessor-1.1.0.tgz", "integrity": "sha1-/Ant8Eu+K7bu6boZaPgmtziAIL0=", "dev": true }, "karma-phantomjs-launcher": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/karma-phantomjs-launcher/-/karma-phantomjs-launcher-1.0.4.tgz", "integrity": "sha1-0jyjSAG9qYY60xjju0vUBisTrNI=", "dev": true, "requires": { "lodash": "^4.0.1", "phantomjs-prebuilt": "^2.1.7" } }, "karma-qunit": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/karma-qunit/-/karma-qunit-1.2.1.tgz", "integrity": "sha1-iCUq/SEnvAOwzDGXjtaIKxOfRwo=", "dev": true }, "kew": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/kew/-/kew-0.7.0.tgz", "integrity": "sha1-edk9LTM2PW/dKXCzNdkUGtWR15s=", "dev": true }, "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } }, "klaw": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", "dev": true, "requires": { "graceful-fs": "^4.1.9" }, "dependencies": { "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true, "optional": true } } }, + "listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha1-hMinKrWcRyUyFIDJdeZQg0LnCTc=", + "dev": true + }, "livereload-js": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/livereload-js/-/livereload-js-2.2.2.tgz", - "integrity": "sha1-bIclfmSKtHW8JOoldFftzB+NC8I=", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/livereload-js/-/livereload-js-2.4.0.tgz", + "integrity": "sha512-XPQH8Z2GDP/Hwz2PCDrh2mth4yFejwA1OZ/81Ti3LgKyhDcEjsSsqFWZojHG0va/duGd+WyosY7eXLDoOyqcPw==", "dev": true }, "load-grunt-tasks": { "version": "3.5.2", "resolved": "https://registry.npmjs.org/load-grunt-tasks/-/load-grunt-tasks-3.5.2.tgz", "integrity": "sha1-ByhWEYD9IP+KaSdQWFL8WKrqDIg=", "dev": true, "requires": { "arrify": "^1.0.0", "multimatch": "^2.0.0", "pkg-up": "^1.0.0", "resolve-pkg": "^0.1.0" } }, "load-json-file": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { "graceful-fs": "^4.1.2", "parse-json": "^2.2.0", "pify": "^2.0.0", "pinkie-promise": "^2.0.0", "strip-bom": "^2.0.0" }, "dependencies": { "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true } } }, "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=", + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", "dev": true }, "lodash._basebind": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._basebind/-/lodash._basebind-2.4.1.tgz", "integrity": "sha1-6UC5690nwyfgqNqxtVkWxTQelXU=", "dev": true, "requires": { "lodash._basecreate": "~2.4.1", "lodash._setbinddata": "~2.4.1", "lodash._slice": "~2.4.1", "lodash.isobject": "~2.4.1" } }, "lodash._basecreate": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._basecreate/-/lodash._basecreate-2.4.1.tgz", "integrity": "sha1-+Ob1tXip405UEXm1a47uv0oofgg=", "dev": true, "requires": { "lodash._isnative": "~2.4.1", "lodash.isobject": "~2.4.1", "lodash.noop": "~2.4.1" } }, "lodash._basecreatecallback": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._basecreatecallback/-/lodash._basecreatecallback-2.4.1.tgz", "integrity": "sha1-fQsmdknLKeehOdAQO3wR+uhOSFE=", "dev": true, "requires": { "lodash._setbinddata": "~2.4.1", "lodash.bind": "~2.4.1", "lodash.identity": "~2.4.1", "lodash.support": "~2.4.1" } }, "lodash._basecreatewrapper": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._basecreatewrapper/-/lodash._basecreatewrapper-2.4.1.tgz", "integrity": "sha1-TTHy595+E0+/KAN2K4FQsyUZZm8=", "dev": true, "requires": { "lodash._basecreate": "~2.4.1", "lodash._setbinddata": "~2.4.1", "lodash._slice": "~2.4.1", "lodash.isobject": "~2.4.1" } }, "lodash._createwrapper": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._createwrapper/-/lodash._createwrapper-2.4.1.tgz", "integrity": "sha1-UdaVeXPaTtVW43KQ2MGhjFPeFgc=", "dev": true, "requires": { "lodash._basebind": "~2.4.1", "lodash._basecreatewrapper": "~2.4.1", "lodash._slice": "~2.4.1", "lodash.isfunction": "~2.4.1" } }, "lodash._isnative": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._isnative/-/lodash._isnative-2.4.1.tgz", "integrity": "sha1-PqZAS3hKe+g2x7V1gOHN95sUgyw=", "dev": true }, "lodash._objecttypes": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._objecttypes/-/lodash._objecttypes-2.4.1.tgz", "integrity": "sha1-fAt/admKH3ZSn4kLDNsbTf7BHBE=", "dev": true }, "lodash._setbinddata": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._setbinddata/-/lodash._setbinddata-2.4.1.tgz", "integrity": "sha1-98IAzRuS7yNrOZ7s9zxkjReqlNI=", "dev": true, "requires": { "lodash._isnative": "~2.4.1", "lodash.noop": "~2.4.1" } }, "lodash._shimkeys": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._shimkeys/-/lodash._shimkeys-2.4.1.tgz", "integrity": "sha1-bpzJZm/wgfC1psl4uD4kLmlJ0gM=", "dev": true, "requires": { "lodash._objecttypes": "~2.4.1" } }, "lodash._slice": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash._slice/-/lodash._slice-2.4.1.tgz", "integrity": "sha1-dFz0GlNZexj2iImFREBe+isG2Q8=", "dev": true }, "lodash.assign": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-2.4.1.tgz", "integrity": "sha1-hMOVlt1xGBqXsGUpE6fJZ15Jsao=", "dev": true, "requires": { "lodash._basecreatecallback": "~2.4.1", "lodash._objecttypes": "~2.4.1", "lodash.keys": "~2.4.1" } }, "lodash.bind": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.bind/-/lodash.bind-2.4.1.tgz", "integrity": "sha1-XRn6AFyMTSNvr0dCx7eh/Kvikmc=", "dev": true, "requires": { "lodash._createwrapper": "~2.4.1", "lodash._slice": "~2.4.1" } }, "lodash.create": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.create/-/lodash.create-2.4.1.tgz", "integrity": "sha1-KnW4ja8mCe/BvURM0aALtncbs2Y=", "dev": true, "requires": { "lodash._basecreate": "~2.4.1", "lodash.assign": "~2.4.1" } }, "lodash.forown": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.forown/-/lodash.forown-2.4.1.tgz", "integrity": "sha1-eLQer+FAX6lmRZ6kGT/VAtCEUks=", "dev": true, "requires": { "lodash._basecreatecallback": "~2.4.1", "lodash._objecttypes": "~2.4.1", "lodash.keys": "~2.4.1" } }, "lodash.identity": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.identity/-/lodash.identity-2.4.1.tgz", "integrity": "sha1-ZpTP+mX++TH3wxzobHRZfPVg9PE=", "dev": true }, "lodash.isarray": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-2.4.1.tgz", "integrity": "sha1-tSoybB9i9tfac6MdVAHfbvRPD6E=", "dev": true, "requires": { "lodash._isnative": "~2.4.1" } }, "lodash.isempty": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.isempty/-/lodash.isempty-2.4.1.tgz", "integrity": "sha1-qGJp15nO84MXyPfnNsa1bT3fScs=", "dev": true, "requires": { "lodash.forown": "~2.4.1", "lodash.isfunction": "~2.4.1" } }, "lodash.isfunction": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-2.4.1.tgz", "integrity": "sha1-LP1XXHPkmKtX4xm3f6Aq3vE6lNE=", "dev": true }, "lodash.isobject": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.isobject/-/lodash.isobject-2.4.1.tgz", "integrity": "sha1-Wi5H/mmVPx7mMafrof5k0tBlWPU=", "dev": true, "requires": { "lodash._objecttypes": "~2.4.1" } }, "lodash.keys": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", "dev": true, "requires": { "lodash._isnative": "~2.4.1", "lodash._shimkeys": "~2.4.1", "lodash.isobject": "~2.4.1" } }, "lodash.noop": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.noop/-/lodash.noop-2.4.1.tgz", "integrity": "sha1-T7VPgWZS5a4Q6PcvcXo4jHMmU4o=", "dev": true }, "lodash.support": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/lodash.support/-/lodash.support-2.4.1.tgz", "integrity": "sha1-Mg4LZwMWc8KNeiu12eAzGkUkBRU=", "dev": true, "requires": { "lodash._isnative": "~2.4.1" } }, "log4js": { "version": "0.6.38", "resolved": "https://registry.npmjs.org/log4js/-/log4js-0.6.38.tgz", "integrity": "sha1-LElBFmldb7JUgJQ9P8hy5mKlIv0=", "dev": true, "requires": { "readable-stream": "~1.0.2", "semver": "~4.3.3" }, "dependencies": { "readable-stream": { "version": "1.0.34", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", "dev": true, "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" } }, "semver": { "version": "4.3.6", "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=", "dev": true } } }, "loud-rejection": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", "dev": true, "requires": { "currently-unhandled": "^0.4.1", "signal-exit": "^3.0.0" } }, "lru-cache": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", "dev": true }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, "map-obj": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", "dev": true }, - "match-stream": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/match-stream/-/match-stream-0.0.2.tgz", - "integrity": "sha1-mesFAJOzTf+t5CG5rAtBCpz6F88=", + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", "dev": true, "requires": { - "buffers": "~0.1.1", - "readable-stream": "~1.0.0" - }, - "dependencies": { - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" - } - } + "object-visit": "^1.0.0" } }, + "math-random": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", + "integrity": "sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==", + "dev": true + }, "maxmin": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/maxmin/-/maxmin-1.1.0.tgz", "integrity": "sha1-cTZehKmd2Piz99X94vANHn9zvmE=", "dev": true, "requires": { "chalk": "^1.0.0", "figures": "^1.0.1", "gzip-size": "^1.0.0", "pretty-bytes": "^1.0.0" } }, "media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", "dev": true }, "meow": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "dev": true, "requires": { "camelcase-keys": "^2.0.0", "decamelize": "^1.1.2", "loud-rejection": "^1.0.0", "map-obj": "^1.0.1", "minimist": "^1.1.3", "normalize-package-data": "^2.3.4", "object-assign": "^4.0.1", "read-pkg-up": "^1.0.1", "redent": "^1.0.0", "trim-newlines": "^1.0.0" }, "dependencies": { "minimist": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", "dev": true } } }, "micromatch": { "version": "2.3.11", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", "dev": true, "requires": { "arr-diff": "^2.0.0", "array-unique": "^0.2.1", "braces": "^1.8.2", "expand-brackets": "^0.1.4", "extglob": "^0.3.1", "filename-regex": "^2.0.0", "is-extglob": "^1.0.0", "is-glob": "^2.0.1", "kind-of": "^3.0.2", "normalize-path": "^2.0.1", "object.omit": "^2.0.0", "parse-glob": "^3.0.4", "regex-cache": "^0.4.2" } }, "mime": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.3.6.tgz", - "integrity": "sha1-WR2E02U6awtKO5343lqoEI5y5eA=", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", "dev": true }, "mime-db": { - "version": "1.29.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.29.0.tgz", - "integrity": "sha1-SNJtI1WJZRcErFkWygYAGRQmaHg=", + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz", + "integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg==", "dev": true }, "mime-types": { - "version": "2.1.16", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.16.tgz", - "integrity": "sha1-K4WKUuXs1RbbiXrCvodIeDBpjiM=", + "version": "2.1.22", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz", + "integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==", "dev": true, "requires": { - "mime-db": "~1.29.0" + "mime-db": "~1.38.0" } }, "minimatch": { "version": "0.2.14", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz", "integrity": "sha1-x054BXT2PG+aCQ6Q775u9TpqdWo=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } }, "minimist": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", "dev": true }, + "mixin-deep": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", + "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, "mkdirp": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "dev": true, "requires": { "minimist": "0.0.8" } }, "ms": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", - "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, "multimatch": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-2.1.0.tgz", "integrity": "sha1-nHkGoi+0wCkZ4vX3UWG0zb1LKis=", "dev": true, "requires": { "array-differ": "^1.0.0", "array-union": "^1.0.1", "arrify": "^1.0.0", "minimatch": "^3.0.0" }, "dependencies": { "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } } } }, "nan": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.6.2.tgz", - "integrity": "sha1-5P805slf37WuzAjeZZb0NgWn20U=", + "version": "2.13.2", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.13.2.tgz", + "integrity": "sha512-TghvYc72wlMGMVMluVo9WRJc0mB8KxxF/gZ4YYFy7V2ZQX9l7rgbPg7vjS9mt6U5HXODVFVI2bOduCzwOMv/lw==", "dev": true, "optional": true }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + } + } + }, "natives": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.0.tgz", - "integrity": "sha1-6f+EFBimsux6SV6TmYT3jxY+bjE=", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.6.tgz", + "integrity": "sha512-6+TDFewD4yxY14ptjKaS63GVdtKiES1pTPyxn9Jb0rBqPMZ7VcCiooEhPNsr+mqHtMGxa/5c/HhcC4uPEUw/nA==", "dev": true }, "negotiator": { "version": "0.4.9", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.9.tgz", "integrity": "sha1-kuRrbbU8fkIe1koryU8IvnYw3z8=", "dev": true }, "nomnom": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/nomnom/-/nomnom-1.8.1.tgz", "integrity": "sha1-IVH3Ikcrp55Qp2/BJbuMjy5Nwqc=", "dev": true, "requires": { "chalk": "~0.4.0", "underscore": "~1.6.0" }, "dependencies": { "ansi-styles": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-1.0.0.tgz", "integrity": "sha1-yxAt8cVvUSPquLZ817mAJ6AnkXg=", "dev": true }, "chalk": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-0.4.0.tgz", "integrity": "sha1-UZmj3c0MHv4jvAjBsCewYXbgxk8=", "dev": true, "requires": { "ansi-styles": "~1.0.0", "has-color": "~0.1.0", "strip-ansi": "~0.1.0" } }, "strip-ansi": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-0.1.1.tgz", "integrity": "sha1-OeipjQRNFQZgq+SmgIrPcLt7yZE=", "dev": true }, "underscore": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.6.0.tgz", "integrity": "sha1-izixDKze9jM3uLJOT/htRa6lKag=", "dev": true } } }, "nopt": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=", "dev": true, "requires": { "abbrev": "1" } }, "normalize-package-data": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", - "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, "requires": { "hosted-git-info": "^2.1.4", - "is-builtin-module": "^1.0.0", + "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" + }, + "dependencies": { + "resolve": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", + "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + } } }, "normalize-path": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", "dev": true, "requires": { "remove-trailing-separator": "^1.0.1" } }, "null-check": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/null-check/-/null-check-1.0.0.tgz", "integrity": "sha1-l33/1xdgErnsMNKjnbXPcqBDnt0=", "dev": true }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", "dev": true }, "oauth-sign": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=", "dev": true }, "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", "dev": true }, - "object-component": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/object-component/-/object-component-0.0.3.tgz", - "integrity": "sha1-8MaapQ78lbhmwYb0AKM3acsvEpE=", - "dev": true + "object-component": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/object-component/-/object-component-0.0.3.tgz", + "integrity": "sha1-8MaapQ78lbhmwYb0AKM3acsvEpE=", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } }, "object.omit": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", "dev": true, "requires": { "for-own": "^0.1.4", "is-extendable": "^0.1.1" } }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, "on-finished": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", "dev": true, "requires": { "ee-first": "1.1.1" } }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { "wrappy": "1" } }, "optimist": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", "dev": true, "requires": { "minimist": "~0.0.1", "wordwrap": "~0.0.2" } }, "options": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz", "integrity": "sha1-7CLTEoBrtT5zF3Pnza788cZDEo8=", "dev": true }, "os-tmpdir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true }, - "over": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/over/-/over-0.0.5.tgz", - "integrity": "sha1-8phS5w/X4l82DgE6jsRMgq7bVwg=", - "dev": true - }, "package": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/package/-/package-1.0.1.tgz", "integrity": "sha1-0lofmeJQbcsn1nBLg9yooxLk7cw=", "dev": true }, "pako": { "version": "0.2.9", "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", "integrity": "sha1-8/dSL073gjSNqBYbrZ7P1Rv4OnU=", "dev": true }, "parse-glob": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", "dev": true, "requires": { "glob-base": "^0.3.0", "is-dotfile": "^1.0.0", "is-extglob": "^1.0.0", "is-glob": "^2.0.0" } }, "parse-json": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { "error-ex": "^1.2.0" } }, "parsejson": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/parsejson/-/parsejson-0.0.1.tgz", "integrity": "sha1-mxDGwNglq1ieaFFTgm3go7oni8w=", "dev": true, "requires": { "better-assert": "~1.0.0" } }, "parseqs": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.2.tgz", "integrity": "sha1-nf5wss3aw4i95PNbHyQPpYrb5sc=", "dev": true, "requires": { "better-assert": "~1.0.0" } }, "parseuri": { "version": "0.0.4", "resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.4.tgz", "integrity": "sha1-gGWCo5iH4eoY3V4v4OAZAiaOk1A=", "dev": true, "requires": { "better-assert": "~1.0.0" } }, "parseurl": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz", - "integrity": "sha1-yKuMkiO6NIiKpkopeyiFO+wY2lY=", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", + "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", + "dev": true + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", "dev": true }, "path-exists": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { "pinkie-promise": "^2.0.0" } }, "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, "path-type": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", "dev": true, "requires": { "graceful-fs": "^4.1.2", "pify": "^2.0.0", "pinkie-promise": "^2.0.0" }, "dependencies": { "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true } } }, "pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", "dev": true }, "performance-now": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-0.2.0.tgz", "integrity": "sha1-M+8wxcd9TqIcWlOGnZG1bY8lVeU=", "dev": true }, "phantomjs-prebuilt": { "version": "2.1.15", "resolved": "https://registry.npmjs.org/phantomjs-prebuilt/-/phantomjs-prebuilt-2.1.15.tgz", "integrity": "sha1-IPhugtM0nFBZF1J3RbekEeCLOQM=", "dev": true, "requires": { "es6-promise": "~4.0.3", "extract-zip": "~1.6.5", "fs-extra": "~1.0.0", "hasha": "~2.2.0", "kew": "~0.7.0", "progress": "~1.1.8", "request": "~2.81.0", "request-progress": "~2.0.1", "which": "~1.2.10" }, "dependencies": { "which": { "version": "1.2.14", "resolved": "https://registry.npmjs.org/which/-/which-1.2.14.tgz", "integrity": "sha1-mofEN48D6CfOyvGs31bHNsAcFOU=", "dev": true, "requires": { "isexe": "^2.0.0" } } } }, "pify": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", "dev": true }, "pinkie": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", "dev": true }, "pinkie-promise": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", "dev": true, "requires": { "pinkie": "^2.0.0" } }, "pkg-up": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-1.0.0.tgz", "integrity": "sha1-Pgj7RhUlxEIWJKM7n35tCvWwWiY=", "dev": true, "requires": { "find-up": "^1.0.0" } }, "platform": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.4.tgz", - "integrity": "sha1-bw+xftqqSPIUQrOpdcBjEw8cPr0=", + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.5.tgz", + "integrity": "sha512-TuvHS8AOIZNAlE77WUDiR4rySV/VMptyMfcfeoMgs4P8apaZM3JrnbzBiixKUv+XR6i+BXrQh8WAnjaSPFO65Q==", + "dev": true + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, "preserve": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", "dev": true }, "pretty-bytes": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-1.0.4.tgz", "integrity": "sha1-CiLoIQYJrTVUL4yNXSFZr/B1HIQ=", "dev": true, "requires": { "get-stdin": "^4.0.1", "meow": "^3.1.0" } }, "process-nextick-args": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", "dev": true }, "progress": { "version": "1.1.8", "resolved": "https://registry.npmjs.org/progress/-/progress-1.1.8.tgz", "integrity": "sha1-4mDHj2Fhzdmw5WzD4Khd4Xx6V74=", "dev": true }, - "pullstream": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/pullstream/-/pullstream-0.4.1.tgz", - "integrity": "sha1-1vs79a7Wl+gxFQ6xACwlo/iuExQ=", - "dev": true, - "requires": { - "over": ">= 0.0.5 < 1", - "readable-stream": "~1.0.31", - "setimmediate": ">= 1.0.2 < 2", - "slice-stream": ">= 1.0.0 < 2" - }, - "dependencies": { - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" - } - } - } + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true }, "punycode": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", "dev": true }, "q": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/q/-/q-1.5.0.tgz", - "integrity": "sha1-3QG6ydBtMObyGa7LglPunr3DCPE=", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", + "integrity": "sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=", "dev": true }, "qjobs": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.1.5.tgz", - "integrity": "sha1-ZZ3p8s+NzCehSBJ28gU3cnI4LnM=", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz", + "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", "dev": true }, "qs": { "version": "6.4.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.4.0.tgz", "integrity": "sha1-E+JtKK1rD/qpExLNO/cI7TUecjM=", "dev": true }, "qunitjs": { "version": "1.23.1", "resolved": "https://registry.npmjs.org/qunitjs/-/qunitjs-1.23.1.tgz", "integrity": "sha1-GXHPl6yb4Bpk0jFVCNLkjm/U5xk=", "dev": true }, "randomatic": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-1.1.7.tgz", - "integrity": "sha512-D5JUjPyJbaJDkuAazpVnSfVkLlpeO3wDlPROTMLGKG1zMFNFRgrciKo1ltz/AzNTkqE0HzDx655QOL51N06how==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz", + "integrity": "sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==", "dev": true, "requires": { - "is-number": "^3.0.0", - "kind-of": "^4.0.0" + "is-number": "^4.0.0", + "kind-of": "^6.0.0", + "math-random": "^1.0.1" }, "dependencies": { "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "^3.0.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } - } - } + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", + "dev": true }, "kind-of": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", - "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", - "dev": true, - "requires": { - "is-buffer": "^1.1.5" - } + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true } } }, "range-parser": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=", "dev": true }, "raw-body": { "version": "2.1.7", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.1.7.tgz", "integrity": "sha1-rf6s4uT7MJgFgBTQjActzFl1h3Q=", "dev": true, "requires": { "bytes": "2.4.0", "iconv-lite": "0.4.13", "unpipe": "1.0.0" }, "dependencies": { "bytes": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-2.4.0.tgz", "integrity": "sha1-fZcZb51br39pNeJZhVSe3SpsIzk=", "dev": true }, "iconv-lite": { "version": "0.4.13", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz", "integrity": "sha1-H4irpKsLFQjoMSrMOTRfNumS4vI=", "dev": true } } }, "read-pkg": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "dev": true, "requires": { "load-json-file": "^1.0.0", "normalize-package-data": "^2.3.2", "path-type": "^1.0.0" } }, "read-pkg-up": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "dev": true, "requires": { "find-up": "^1.0.0", "read-pkg": "^1.0.0" } }, "readable-stream": { "version": "1.1.14", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", "dev": true, "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" } }, "readdirp": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.1.0.tgz", - "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", + "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", "dev": true, "requires": { - "graceful-fs": "^4.1.2", - "minimatch": "^3.0.2", - "readable-stream": "^2.0.2", - "set-immediate-shim": "^1.0.1" + "graceful-fs": "^4.1.11", + "micromatch": "^3.1.10", + "readable-stream": "^2.0.2" }, "dependencies": { + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", "dev": true }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", "dev": true, "requires": { - "brace-expansion": "^1.1.7" + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" } }, "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", - "process-nextick-args": "~1.0.6", + "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", - "string_decoder": "~1.0.3", + "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "requires": { "safe-buffer": "~5.1.0" } } } }, "redent": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", "dev": true, "requires": { "indent-string": "^2.1.0", "strip-indent": "^1.0.1" } }, "regex-cache": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.3.tgz", - "integrity": "sha1-mxpsNdTQ3871cRrmUejp09cRQUU=", + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", + "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", "dev": true, "requires": { - "is-equal-shallow": "^0.1.3", - "is-primitive": "^2.0.0" + "is-equal-shallow": "^0.1.3" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" } }, "remove-trailing-separator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", "dev": true }, "repeat-element": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", - "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=", + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", "dev": true }, "repeat-string": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", "dev": true }, "repeating": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", "dev": true, "requires": { "is-finite": "^1.0.0" } }, "request": { "version": "2.81.0", "resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz", "integrity": "sha1-xpKJRqDgbF+Nb4qTM0af/aRimKA=", "dev": true, "requires": { "aws-sign2": "~0.6.0", "aws4": "^1.2.1", "caseless": "~0.12.0", "combined-stream": "~1.0.5", "extend": "~3.0.0", "forever-agent": "~0.6.1", "form-data": "~2.1.1", "har-validator": "~4.2.1", "hawk": "~3.1.3", "http-signature": "~1.1.0", "is-typedarray": "~1.0.0", "isstream": "~0.1.2", "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.7", "oauth-sign": "~0.8.1", "performance-now": "^0.2.0", "qs": "~6.4.0", "safe-buffer": "^5.0.1", "stringstream": "~0.0.4", "tough-cookie": "~2.3.0", "tunnel-agent": "^0.6.0", "uuid": "^3.0.0" } }, "request-progress": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/request-progress/-/request-progress-2.0.1.tgz", "integrity": "sha1-XTa7V5YcZzqlt4jbyBQf3yO0Tgg=", "dev": true, "requires": { "throttleit": "^1.0.0" } }, "requirejs": { "version": "2.3.5", "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.5.tgz", "integrity": "sha512-svnO+aNcR/an9Dpi44C7KSAy5fFGLtmPbaaCeQaklUz8BQhS64tWWIIlvEA5jrWICzlO/X9KSzSeXFnZdBu8nw==", "dev": true }, "requirejs-domready": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/requirejs-domready/-/requirejs-domready-2.0.3.tgz", "integrity": "sha1-BJ2xlljPrAdIWVLTUhMFq4NtrFI=", "dev": true }, "requirejs-text": { "version": "2.0.15", "resolved": "https://registry.npmjs.org/requirejs-text/-/requirejs-text-2.0.15.tgz", "integrity": "sha1-ExOHM2E/xEV7fhJH6Mt1HfeqVCk=", "dev": true }, "requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", "dev": true }, "resolve": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/resolve/-/resolve-0.3.1.tgz", "integrity": "sha1-NMY0R8ZkxwWY0cmxJvxDsqJDEKQ=", "dev": true }, "resolve-from": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", "dev": true }, "resolve-pkg": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/resolve-pkg/-/resolve-pkg-0.1.0.tgz", "integrity": "sha1-AsyZNBDik2livZcWahsHfalyVTE=", "dev": true, "requires": { "resolve-from": "^2.0.0" } }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, "rimraf": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", "integrity": "sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI=", "dev": true }, "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true }, - "semver": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", - "integrity": "sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==", + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, - "set-immediate-shim": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", - "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=", + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", "dev": true }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, "setimmediate": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", "dev": true }, "shelljs": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.3.0.tgz", "integrity": "sha1-NZbmMHp4FUT1kfN9phg2DzHbV7E=", "dev": true }, "sigmund": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", "dev": true }, "signal-exit": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true }, - "slice-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-stream/-/slice-stream-1.0.0.tgz", - "integrity": "sha1-WzO9ZvATsaf4ZGCwPUY97DmtPqA=", + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", "dev": true, "requires": { - "readable-stream": "~1.0.31" + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" }, "dependencies": { - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true } } }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + } + }, "sntp": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/sntp/-/sntp-1.0.9.tgz", "integrity": "sha1-ZUEYTMkK7qbG57NeJlkIJEPGYZg=", "dev": true, "requires": { "hoek": "2.x.x" } }, "socket.io": { "version": "1.4.7", "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-1.4.7.tgz", "integrity": "sha1-krf3y4jFeX1NruJ5/oB12+bT+hw=", "dev": true, "requires": { "debug": "2.2.0", "engine.io": "1.6.10", "has-binary": "0.1.7", "socket.io-adapter": "0.4.0", "socket.io-client": "1.4.6", "socket.io-parser": "2.2.6" + }, + "dependencies": { + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + } } }, "socket.io-adapter": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-0.4.0.tgz", "integrity": "sha1-+5+CqxqmUpC/csNleVW5MKmRok8=", "dev": true, "requires": { "debug": "2.2.0", "socket.io-parser": "2.2.2" }, "dependencies": { "benchmark": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-1.0.0.tgz", "integrity": "sha1-Lx4vpMNZ8REiqhgwgiGOlX45DHM=", "dev": true }, + "component-emitter": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", + "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", + "dev": true + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + }, "socket.io-parser": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-2.2.2.tgz", "integrity": "sha1-PXr2tkSX6Va32f53X5mXFgJ/lBc=", "dev": true, "requires": { "benchmark": "1.0.0", "component-emitter": "1.1.2", "debug": "0.7.4", "isarray": "0.0.1", "json3": "3.2.6" }, "dependencies": { "debug": { "version": "0.7.4", "resolved": "https://registry.npmjs.org/debug/-/debug-0.7.4.tgz", "integrity": "sha1-BuHqgILCyxTjmAbiLi9vdX+Srzk=", "dev": true } } } } }, "socket.io-client": { "version": "1.4.6", "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-1.4.6.tgz", "integrity": "sha1-SbC6U379FbgpfIQBbmQuHHx1LD0=", "dev": true, "requires": { "backo2": "1.0.2", "component-bind": "1.0.0", "component-emitter": "1.2.0", "debug": "2.2.0", "engine.io-client": "1.6.9", "has-binary": "0.1.7", "indexof": "0.0.1", "object-component": "0.0.3", "parseuri": "0.0.4", "socket.io-parser": "2.2.6", "to-array": "0.1.4" }, "dependencies": { "component-emitter": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.0.tgz", "integrity": "sha1-zNETqGOI0GSC0D3j/H35hSa6jv4=", "dev": true + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true } } }, "socket.io-parser": { "version": "2.2.6", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-2.2.6.tgz", "integrity": "sha1-ON/WHfUNz4qx2eIJEyK/kCuii5k=", "dev": true, "requires": { "benchmark": "1.0.0", "component-emitter": "1.1.2", "debug": "2.2.0", "isarray": "0.0.1", "json3": "3.3.2" }, "dependencies": { "benchmark": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-1.0.0.tgz", "integrity": "sha1-Lx4vpMNZ8REiqhgwgiGOlX45DHM=", "dev": true }, + "component-emitter": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", + "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", + "dev": true + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, "json3": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.2.tgz", "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=", "dev": true + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true } } }, "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "dev": true, + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, "spawnback": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/spawnback/-/spawnback-1.0.0.tgz", "integrity": "sha1-9zZi9+VNlTZ+ynTWQmxnfdfqaG8=", "dev": true }, "spdx-correct": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-1.0.2.tgz", - "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", + "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", "dev": true, "requires": { - "spdx-license-ids": "^1.0.2" + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" } }, - "spdx-expression-parse": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz", - "integrity": "sha1-m98vIOH0DtRH++JzJmGR/O1RYmw=", + "spdx-exceptions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", + "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", "dev": true }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, "spdx-license-ids": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", - "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz", + "integrity": "sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA==", "dev": true }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, "sshpk": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.13.1.tgz", - "integrity": "sha1-US322mKHFEMW3EwY/hzx2UBzm+M=", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", "dev": true, "requires": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", "bcrypt-pbkdf": "^1.0.0", "dashdash": "^1.12.0", "ecc-jsbn": "~0.1.1", "getpass": "^0.1.1", "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", "tweetnacl": "~0.14.0" }, "dependencies": { "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true } } }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, "statuses": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", - "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", "dev": true }, "string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", "dev": true }, "stringstream": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.5.tgz", - "integrity": "sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=", + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.6.tgz", + "integrity": "sha512-87GEBAkegbBcweToUrdzf3eLhWNg06FJTebl4BVJz/JgWy8CvEr9dRtX5qWphiynMSQlxxi+QqN0z5T32SLlhA==", "dev": true }, "strip-ansi": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { "ansi-regex": "^2.0.0" } }, "strip-bom": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", "dev": true, "requires": { "is-utf8": "^0.2.0" } }, "strip-indent": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", "dev": true, "requires": { "get-stdin": "^4.0.1" } }, "strip-json-comments": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=", "dev": true }, "supports-color": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", "dev": true }, "temporary": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/temporary/-/temporary-0.0.8.tgz", "integrity": "sha1-oYqYHSi6jKNgJ/s8MFOMPst0CsA=", "dev": true, "requires": { "package": ">= 1.0.0 < 1.2.0" } }, "throttleit": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-1.0.0.tgz", "integrity": "sha1-nnhYNtr0Z0MUWlmEtiaNgoUorGw=", "dev": true }, "tiny-lr": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/tiny-lr/-/tiny-lr-0.2.1.tgz", "integrity": "sha1-s/26gC5dVqM8L28QeUsy5Hescp0=", "dev": true, "requires": { "body-parser": "~1.14.0", "debug": "~2.2.0", "faye-websocket": "~0.10.0", "livereload-js": "^2.2.0", "parseurl": "~1.3.0", "qs": "~5.1.0" }, "dependencies": { + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + }, "qs": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/qs/-/qs-5.1.0.tgz", "integrity": "sha1-TZMuXH6kEcynajEtOaYGIA/VDNk=", "dev": true } } }, "tmp": { "version": "0.0.28", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.28.tgz", "integrity": "sha1-Fyc1t/YU6nrzlmT6hM8N5OUV0SA=", "dev": true, "requires": { "os-tmpdir": "~1.0.1" } }, "to-array": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz", "integrity": "sha1-F+bBH3PdTz10zaek/zI46a2b+JA=", "dev": true }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + } + } + }, "tough-cookie": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.2.tgz", - "integrity": "sha1-8IH3bkyFcg5sN6X6ztc3FQ2EByo=", + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.4.tgz", + "integrity": "sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==", "dev": true, "requires": { "punycode": "^1.4.1" } }, "traverse": { "version": "0.3.9", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", "integrity": "sha1-cXuPIgzAu3tE5AUUwisui7xw2Lk=", "dev": true }, "trim-newlines": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", "dev": true }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", "dev": true, "requires": { "safe-buffer": "^5.0.1" } }, "tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", - "dev": true, - "optional": true + "dev": true }, "type-is": { - "version": "1.6.15", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.15.tgz", - "integrity": "sha1-yrEPtJCeRByChC6v4a1kbIGARBA=", + "version": "1.6.16", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", + "integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", "dev": true, "requires": { "media-typer": "0.3.0", - "mime-types": "~2.1.15" + "mime-types": "~2.1.18" } }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, "uglify-js": { "version": "3.0.28", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.0.28.tgz", "integrity": "sha512-0h/qGay016GG2lVav3Kz174F3T2Vjlz2v6HCt+WDQpoXfco0hWwF5gHK9yh88mUYvIC+N7Z8NT8WpjSp1yoqGA==", "dev": true, "requires": { "commander": "~2.11.0", "source-map": "~0.5.1" } }, "ultron": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.2.tgz", "integrity": "sha1-rOEWq1V80Zc4ak6I9GhTeMiy5Po=", "dev": true }, "underscore": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.7.0.tgz", "integrity": "sha1-a7rwh3UA02vjTsqlhODbn+8DUgk=", "dev": true }, "underscore.string": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.2.1.tgz", "integrity": "sha1-18D6KvXVoaZ/QlPa7pgTLnM/Dxk=", "dev": true }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" + } + } + } + }, "unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", "dev": true }, - "unzip": { - "version": "0.1.11", - "resolved": "https://registry.npmjs.org/unzip/-/unzip-0.1.11.tgz", - "integrity": "sha1-iXScY7BY19kNYZ+GuYqhU107l/A=", + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "unzipper": { + "version": "0.9.11", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.9.11.tgz", + "integrity": "sha512-G0z5zv8LYv4/XwpOiXgTGTcN4jyxgyg3P1DfdIeCN2QGOd6ZBl49BSbOe9JsIEvKh3tG7/b0bdJvz+UmwA+BRg==", "dev": true, "requires": { - "binary": ">= 0.3.0 < 1", - "fstream": ">= 0.1.30 < 1", - "match-stream": ">= 0.0.2 < 1", - "pullstream": ">= 0.4.1 < 1", - "readable-stream": "~1.0.31", - "setimmediate": ">= 1.0.1 < 2" + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "~1.0.10", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" }, "dependencies": { + "bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha1-9y12C+Cbf3bQjtj66Ysomo0F+rM=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "requires": { "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" } } } }, "uri-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/uri-path/-/uri-path-1.0.0.tgz", "integrity": "sha1-l0fwGDWJM8Md4PzP2C0TjmcmLjI=", "dev": true }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, "useragent": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/useragent/-/useragent-2.2.1.tgz", - "integrity": "sha1-z1k+9PLRdYdei7ZY6pLhik/QbY4=", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/useragent/-/useragent-2.3.0.tgz", + "integrity": "sha512-4AoH4pxuSvHCjqLO04sU6U/uE65BYza8l/KKBS0b0hnUPWi+cQ2BpeTEwejCSx9SPV5/U03nniDTrWx5NrmKdw==", "dev": true, "requires": { - "lru-cache": "2.2.x", + "lru-cache": "4.1.x", "tmp": "0.0.x" }, "dependencies": { "lru-cache": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.2.4.tgz", - "integrity": "sha1-bGWGGb7PFAMdDQtZSxYELOTcBj0=", - "dev": true + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } } } }, "utf8": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/utf8/-/utf8-2.1.0.tgz", "integrity": "sha1-DP7FyAUtRKI+OqqQgQToB1+V39U=", "dev": true }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, "utils-merge": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", - "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", "dev": true }, "uuid": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.1.0.tgz", - "integrity": "sha512-DIWtzUkw04M4k3bf1IcpS2tngXEL26YUD2M0tMDUpnUrz2hgzUBlD55a4FjdLGPvfHxS6uluGWvaVEqgBcVa+g==", + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", "dev": true }, "validate-npm-package-license": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz", - "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", "dev": true, "requires": { - "spdx-correct": "~1.0.0", - "spdx-expression-parse": "~1.0.0" + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" } }, "verror": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "dev": true, "requires": { "assert-plus": "^1.0.0", "core-util-is": "1.0.2", "extsprintf": "^1.2.0" }, "dependencies": { "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", "dev": true } } }, "void-elements": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=", "dev": true }, "vow": { - "version": "0.4.16", - "resolved": "https://registry.npmjs.org/vow/-/vow-0.4.16.tgz", - "integrity": "sha1-u51U2TjV+AUg1linQOeoleMP7us=", + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/vow/-/vow-0.4.19.tgz", + "integrity": "sha512-S+0+CiQlbUhTNWMlJdqo/ARuXOttXdvw5ACGyh1W97NFHUdwt3Fzyaus03Kvdmo733dwnYS9AGJSDg0Zu8mNfA==", "dev": true }, "vow-fs": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/vow-fs/-/vow-fs-0.3.6.tgz", "integrity": "sha1-LUxZviLivyYY3fWXq0uqkjvnIA0=", "dev": true, "requires": { "glob": "^7.0.5", "uuid": "^2.0.2", "vow": "^0.4.7", "vow-queue": "^0.4.1" }, "dependencies": { "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { "brace-expansion": "^1.1.7" } }, "uuid": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/uuid/-/uuid-2.0.3.tgz", "integrity": "sha1-Z+LoY3lyFVMN/zGOW/nc6/1Hsho=", "dev": true } } }, "vow-queue": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/vow-queue/-/vow-queue-0.4.2.tgz", - "integrity": "sha1-5/4XFg4Vx8QYTRtmapvGThjjAYQ=", + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/vow-queue/-/vow-queue-0.4.3.tgz", + "integrity": "sha512-/poAKDTFL3zYbeQg7cl4BGcfP4sGgXKrHnRFSKj97dteUFu8oyXMwIcdwu8NSx/RmPGIuYx1Bik/y5vU4H/VKw==", "dev": true, "requires": { - "vow": "~0.4.0" + "vow": "^0.4.17" } }, "websocket-driver": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.6.5.tgz", - "integrity": "sha1-XLJVbOuF9Dc8bYI4qmkchFThOjY=", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", + "integrity": "sha1-DK+dLXVdk67gSdS90NP+LMoqJOs=", "dev": true, "requires": { + "http-parser-js": ">=0.4.0", "websocket-extensions": ">=0.1.1" } }, "websocket-extensions": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.1.tgz", - "integrity": "sha1-domUmcGEtu91Q3fC27DNbLVdKec=", + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", + "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==", "dev": true }, "which": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/which/-/which-1.0.9.tgz", "integrity": "sha1-RgwdoPgQED0DIam2M6+eV15kSG8=", "dev": true }, "wordwrap": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", "dev": true }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, "ws": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ws/-/ws-1.0.1.tgz", "integrity": "sha1-fQsqLljN3YGQOcKcneZQReGzEOk=", "dev": true, "requires": { "options": ">=0.0.5", "ultron": "1.0.x" } }, "xmlbuilder": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-2.3.0.tgz", "integrity": "sha1-hniR+rlWg1racSJ+U6mVMjVlk60=", "dev": true, "requires": { "lodash.assign": "~2.4.1", "lodash.create": "~2.4.1", "lodash.isarray": "~2.4.1", "lodash.isempty": "~2.4.1", "lodash.isfunction": "~2.4.1", "lodash.isobject": "~2.4.1" } }, "xmlhttprequest-ssl": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.1.tgz", "integrity": "sha1-O3dB/qSoZnWXbpCNKW1ERZYfqmc=", "dev": true }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + }, "yauzl": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.4.1.tgz", "integrity": "sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU=", "dev": true, "requires": { "fd-slicer": "~1.0.1" } }, "yeast": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz", "integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk=", "dev": true } } }
jquery/sizzle
67e9691e8689b824387affb9da06dc663da63598
Selector: Stop using innerText in :contains
diff --git a/dist/sizzle.js b/dist/sizzle.js index 150d90c..1065e13 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -1,521 +1,521 @@ /*! * Sizzle CSS Selector Engine v2.3.4-pre * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * - * Date: 2018-12-03 + * Date: 2019-01-14 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } @@ -955,1025 +955,1025 @@ setDocument = Sizzle.setDocument = function( node ) { while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, diff --git a/dist/sizzle.min.js b/dist/sizzle.min.js index d4ea5ac..0e403e4 100644 --- a/dist/sizzle.min.js +++ b/dist/sizzle.min.js @@ -1,3 +1,3 @@ /*! Sizzle v2.3.4-pre | (c) JS Foundation and other contributors | js.foundation */ -!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),S=ae(),A=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); +!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),S=ae(),A=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); //# sourceMappingURL=sizzle.min.map \ No newline at end of file diff --git a/dist/sizzle.min.map b/dist/sizzle.min.map index 10d432c..876174e 100644 --- a/dist/sizzle.min.map +++ b/dist/sizzle.min.map @@ -1 +1 @@ -{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","push_native","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","last","simple","forward","ofType","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","innerText","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAWA,GAEX,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GAIRsB,KAAcC,eACdC,KACAC,EAAMD,EAAIC,IACVC,EAAcF,EAAIG,KAClBA,EAAOH,EAAIG,KACXC,EAAQJ,EAAII,MAGZC,EAAU,SAAUC,EAAMC,GAGzB,IAFA,IAAIzC,EAAI,EACP0C,EAAMF,EAAKG,OACJ3C,EAAI0C,EAAK1C,IAChB,GAAKwC,EAAKxC,KAAOyC,EAChB,OAAOzC,EAGT,OAAQ,GAGT4C,EAAW,6HAKXC,EAAa,sBAGbC,EAAa,gCAGbC,EAAa,MAAQF,EAAa,KAAOC,EAAa,OAASD,EAE9D,gBAAkBA,EAElB,2DAA6DC,EAAa,OAASD,EACnF,OAEDG,EAAU,KAAOF,EAAa,wFAKAC,EAAa,eAM3CE,EAAc,IAAIC,OAAQL,EAAa,IAAK,KAC5CM,EAAQ,IAAID,OAAQ,IAAML,EAAa,8BAAgCA,EAAa,KAAM,KAE1FO,EAAS,IAAIF,OAAQ,IAAML,EAAa,KAAOA,EAAa,KAC5DQ,EAAe,IAAIH,OAAQ,IAAML,EAAa,WAAaA,EAAa,IAAMA,EAAa,KAC3FS,EAAW,IAAIJ,OAAQL,EAAa,MAEpCU,EAAU,IAAIL,OAAQF,GACtBQ,EAAc,IAAIN,OAAQ,IAAMJ,EAAa,KAE7CW,GACCC,GAAM,IAAIR,OAAQ,MAAQJ,EA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YAAe4F,GAAO,SAAUC,GAG7C,OAFAA,EAAGyC,UAAY,WACfzC,EAAG8E,WAAW/F,aAAc,QAAS,IACY,KAA1CiB,EAAG8E,WAAWjG,aAAc,YAEnCsB,GAAW,QAAS,SAAUtG,EAAMiK,EAAMtM,GACzC,IAAMA,GAAyC,UAAhCqC,EAAKiD,SAASC,cAC5B,OAAOlD,EAAKkT,eAOThN,GAAO,SAAUC,GACtB,OAAsC,MAA/BA,EAAGnB,aAAa,eAEvBsB,GAAWnG,EAAU,SAAUH,EAAMiK,EAAMtM,GAC1C,IAAIuM,EACJ,IAAMvM,EACL,OAAwB,IAAjBqC,EAAMiK,GAAkBA,EAAK/G,eACjCgH,EAAMlK,EAAKwI,iBAAkByB,KAAWC,EAAIE,UAC7CF,EAAIrE,MACL,OAMJ,IAAIsN,GAAU7V,EAAOuG,OAErBA,GAAOuP,WAAa,WAKnB,OAJK9V,EAAOuG,SAAWA,KACtBvG,EAAOuG,OAASsP,IAGVtP,IAGe,mBAAXwP,QAAyBA,OAAOC,IAC3CD,OAAO,WAAa,OAAOxP,KAEE,oBAAX0P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU3P,GAEjBvG,EAAOuG,OAASA,GA3tEjB,CA+tEIvG","file":"sizzle.min.js"} \ No newline at end of file +{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","push_native","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","last","simple","forward","ofType","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAWA,GAEX,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAAOa,SACtBU,EAAU,EACVC,EAAO,EACPC,EAAaC,KACbC,EAAaD,KACbE,EAAgBF,KAChBG,EAAyBH,KACzBI,EAAY,SAAUC,EAAGC,GAIxB,OAHKD,IAAMC,IACVrB,GAAe,GAET,GAIRsB,KAAcC,eACdC,KACAC,EAAMD,EAAIC,IACVC,EAAcF,EAAIG,KAClBA,EAAOH,EAAIG,KACXC,EAAQJ,EAAII,MAGZC,EAAU,SAAUC,EAAMC,GAGzB,IAFA,IAAIzC,EAAI,EACP0C,EAAMF,EAAKG,OACJ3C,EAAI0C,EAAK1C,IAChB,GAAKwC,EAAKxC,KAAOyC,EAChB,OAAOzC,EAGT,OAAQ,GAGT4C,EAAW,6HAKXC,EAAa,sBAGbC,EAAa,gCAGbC,EAAa,MAAQF,EAAa,KAAOC,EAAa,OAASD,EAE9D,gBAAkBA,EAElB,2DAA6DC,EAAa,OAASD,EACnF,OAEDG,EAAU,KAAOF,EAAa,wFAKAC,EAAa,eAM3CE,EAAc,IAAIC,OAAQL,EAAa,IAAK,KAC5CM,EAAQ,IAAID,OAAQ,IAAML,EAAa,8BAAgCA,EAAa,KAAM,KAE1FO,EAAS,IAAIF,OAAQ,IAAML,EAAa,KAAOA,EAAa,KAC5DQ,EAAe,IAAIH,OAAQ,IAAML,EAAa,W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AAa,WAElCsB,GAAW,yBAA0B,SAAUtG,EAAMiK,EAAMtM,GAC1D,IAAMA,EACL,OAAOqC,EAAKgF,aAAciF,EAA6B,SAAvBA,EAAK/G,cAA2B,EAAI,KAOjE1F,EAAQ8C,YAAe4F,GAAO,SAAUC,GAG7C,OAFAA,EAAGyC,UAAY,WACfzC,EAAG8E,WAAW/F,aAAc,QAAS,IACY,KAA1CiB,EAAG8E,WAAWjG,aAAc,YAEnCsB,GAAW,QAAS,SAAUtG,EAAMiK,EAAMtM,GACzC,IAAMA,GAAyC,UAAhCqC,EAAKiD,SAASC,cAC5B,OAAOlD,EAAKiT,eAOT/M,GAAO,SAAUC,GACtB,OAAsC,MAA/BA,EAAGnB,aAAa,eAEvBsB,GAAWnG,EAAU,SAAUH,EAAMiK,EAAMtM,GAC1C,IAAIuM,EACJ,IAAMvM,EACL,OAAwB,IAAjBqC,EAAMiK,GAAkBA,EAAK/G,eACjCgH,EAAMlK,EAAKwI,iBAAkByB,KAAWC,EAAIE,UAC7CF,EAAIrE,MACL,OAMJ,IAAIqN,GAAU5V,EAAOuG,OAErBA,GAAOsP,WAAa,WAKnB,OAJK7V,EAAOuG,SAAWA,KACtBvG,EAAOuG,OAASqP,IAGVrP,IAGe,mBAAXuP,QAAyBA,OAAOC,IAC3CD,OAAO,WAAa,OAAOvP,KAEE,oBAAXyP,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU1P,GAEjBvG,EAAOuG,OAASA,GA3tEjB,CA+tEIvG","file":"sizzle.min.js"} \ No newline at end of file diff --git a/src/sizzle.js b/src/sizzle.js index 868342d..66b8577 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -955,1025 +955,1025 @@ setDocument = Sizzle.setDocument = function( node ) { while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, diff --git a/test/unit/selector.js b/test/unit/selector.js index 6c04b15..3117daa 100644 --- a/test/unit/selector.js +++ b/test/unit/selector.js @@ -321,1051 +321,1064 @@ QUnit.test("name", function( assert ) { var form; t( "Name selector", "input[name=action]", ["text1"] ); t( "Name selector with single quotes", "input[name='action']", ["text1"] ); t( "Name selector with double quotes", "input[name=\"action\"]", ["text1"] ); t( "Name selector non-input", "[name=example]", ["name-is-example"] ); t( "Name selector non-input", "[name=div]", ["name-is-div"] ); t( "Name selector non-input", "*[name=iframe]", ["iframe"] ); t( "Name selector for grouped input", "input[name='types[]']", ["types_all", "types_anime", "types_movie"] ); form = document.getElementById("form"); assert.deepEqual( Sizzle("input[name=action]", form), q("text1"), "Name selector within the context of another element" ); assert.deepEqual( Sizzle("input[name='foo[bar]']", form), q("hidden2"), "Name selector for grouped form element within the context of another element" ); form = jQuery("<form><input name='id'/></form>").appendTo("body"); assert.equal( Sizzle("input", form[0]).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); form.remove(); t( "Find elements that have similar IDs", "[name=tName1]", ["tName1ID"] ); t( "Find elements that have similar IDs", "[name=tName2]", ["tName2ID"] ); t( "Find elements that have similar IDs", "#tName2ID", ["tName2ID"] ); t( "Case-sensitivity", "[name=tname1]", [] ); }); QUnit.test( "multiple", function( assert ) { assert.expect( 6 ); jQuery( "#qunit-fixture" ).prepend( "<h2 id='h2'/>" ); t( "Comma Support", "#qunit-fixture h2, #qunit-fixture p", [ "h2","firstp","ap","sndp","en","sap","first" ] ); t( "Comma Support", "#qunit-fixture h2 , #qunit-fixture p", [ "h2","firstp","ap","sndp","en","sap","first" ] ); t( "Comma Support", "#qunit-fixture h2 , #qunit-fixture p", [ "h2","firstp","ap","sndp","en","sap","first" ] ); t( "Comma Support", "#qunit-fixture h2,#qunit-fixture p", [ "h2","firstp","ap","sndp","en","sap","first" ] ); t( "Comma Support", "#qunit-fixture h2,#qunit-fixture p ", [ "h2","firstp","ap","sndp","en","sap","first" ] ); t( "Comma Support", "#qunit-fixture h2\t,\r#qunit-fixture p\n", [ "h2","firstp","ap","sndp","en","sap","first" ] ); }); QUnit.test("child and adjacent", function( assert ) { assert.expect( 43 ); var siblingFirst, en, nothiddendiv; t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child minus whitespace", "p>a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child minus trailing whitespace", "p> a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child minus leading whitespace", "p >a", ["simon1","google","groups","mark","yahoo","simon"] ); t( "Child w/ Class", "p > a.blog", ["mark","simon"] ); t( "All Children", "code > *", ["anchor1","anchor2"] ); t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] ); t( "Rooted tag adjacent", "#qunit-fixture a + a", ["groups", "tName2ID"] ); t( "Rooted tag adjacent minus whitespace", "#qunit-fixture a+a", ["groups", "tName2ID"] ); t( "Rooted tag adjacent minus leading whitespace", "#qunit-fixture a +a", ["groups", "tName2ID"] ); t( "Rooted tag adjacent minus trailing whitespace", "#qunit-fixture a+ a", ["groups", "tName2ID"] ); t( "Tag adjacent", "p + p", ["ap","en","sap"] ); t( "#id adjacent", "#firstp + p", ["ap"] ); t( "Tag#id adjacent", "p#firstp + p", ["ap"] ); t( "Tag[attr] adjacent", "p[lang=en] + p", ["sap"] ); t( "Tag.class adjacent", "a.GROUPS + code + a", ["mark"] ); t( "Comma, Child, and Adjacent", "#qunit-fixture a + a, code > a", ["groups","anchor1","anchor2","tName2ID"] ); t( "Element Preceded By", "#qunit-fixture p ~ div", ["foo", "nothiddendiv", "moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#first ~ div", ["moretests","tabindex-tests", "liveHandlerOrder", "siblingTest"] ); t( "Element Preceded By", "#groups ~ a", ["mark"] ); t( "Element Preceded By", "#length ~ input", ["idTest"] ); t( "Element Preceded By", "#siblingfirst ~ em", ["siblingnext", "siblingthird"] ); t( "Element Preceded By (multiple)", "#siblingTest em ~ em ~ em ~ span", ["siblingspan"] ); t( "Element Preceded By, Containing", "#liveHandlerOrder ~ div em:contains('1')", ["siblingfirst"] ); siblingFirst = document.getElementById("siblingfirst"); assert.deepEqual( Sizzle("~ em", siblingFirst), q("siblingnext", "siblingthird"), "Element Preceded By with a context." ); assert.deepEqual( Sizzle("+ em", siblingFirst), q("siblingnext"), "Element Directly Preceded By with a context." ); assert.deepEqual( Sizzle("~ em:first", siblingFirst), q("siblingnext"), "Element Preceded By positional with a context." ); en = document.getElementById("en"); assert.deepEqual( Sizzle("+ p, a", en), q("yahoo", "sap"), "Compound selector with context, beginning with sibling test." ); assert.deepEqual( Sizzle("a, + p", en), q("yahoo", "sap"), "Compound selector with context, containing sibling test." ); t( "Multiple combinators selects all levels", "#siblingTest em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple combinators selects all levels", "#siblingTest > em *", ["siblingchild", "siblinggrandchild", "siblinggreatgrandchild"] ); t( "Multiple sibling combinators doesn't miss general siblings", "#siblingTest > em:first-child + em ~ span", ["siblingspan"] ); t( "Combinators are not skipped when mixing general and specific", "#siblingTest > em:contains('x') + em ~ span", [] ); assert.equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for next test is found via ID (#8310)" ); assert.equal( Sizzle("#listWithTabIndex li:eq(2) ~ li").length, 1, "Find by general sibling combinator (#8310)" ); assert.equal( Sizzle("#__sizzle__").length, 0, "Make sure the temporary id assigned by sizzle is cleared out (#8310)" ); assert.equal( Sizzle("#listWithTabIndex").length, 1, "Parent div for previous test is still found via ID (#8310)" ); t( "Verify deep class selector", "div.blah > p > a", [] ); t( "No element deep selector", "div.foo > span > a", [] ); nothiddendiv = document.getElementById("nothiddendiv"); assert.deepEqual( Sizzle("> :first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); assert.deepEqual( Sizzle("> :eq(0)", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); assert.deepEqual( Sizzle("> *:first", nothiddendiv), q("nothiddendivchild"), "Verify child context positional selector" ); t( "Non-existant ancestors", ".fototab > .thumbnails > a", [] ); }); QUnit.test("attributes - existence", function( assert ) { assert.expect( 7 ); t( "on element", "#qunit-fixture a[title]", [ "google" ] ); t( "on element (whitespace ignored)", "#qunit-fixture a[ title ]", [ "google" ] ); t( "on element (case-insensitive)", "#qunit-fixture a[TITLE]", [ "google" ] ); t( "on any element", "#qunit-fixture *[title]", [ "google" ] ); t( "on implicit element", "#qunit-fixture [title]", [ "google" ] ); t( "boolean", "#select2 option[selected]", [ "option2d" ]); t( "for attribute on label", "form label[for]", [ "label-for" ] ); }); QUnit.test("attributes - equals", function( assert ) { assert.expect( 20 ); t( "identifier", "#qunit-fixture a[rel=bookmark]", [ "simon1" ] ); t( "identifier containing underscore", "input[id=types_all]", ["types_all"] ); t( "string", "#qunit-fixture a[rel='bookmark']", [ "simon1" ] ); t( "string (whitespace ignored)", "#qunit-fixture a[ rel = 'bookmark' ]", [ "simon1" ] ); t( "non-identifier string", "#qunit-fixture a[href='http://www.google.com/']", [ "google" ] ); t( "empty string", "#select1 option[value='']", [ "option1a" ] ); t( "number", "#qunit-fixture option[value=1]", [ "option1b", "option2b", "option3b", "option4b", "option5c" ] ); t( "negative number", "#qunit-fixture li[tabIndex=-1]", [ "foodWithNegativeTabIndex" ] ); t( "non-ASCII identifier", "span[lang=中文]", ["台北"] ); t( "input[type=text]", "#form input[type=text]", [ "text1", "text2", "hidden2", "name" ] ); t( "input[type=search]", "#form input[type=search]", [ "search" ] ); t( "script[src] (jQuery #13777)", "#moretests script[src]", [ "script-src" ] ); t( "boolean attribute equals name", "#select2 option[selected='selected']", [ "option2d" ]); t( "for attribute in form", "#form [for=action]", [ "label-for" ] ); t( "name attribute", "input[name='foo[bar]']", [ "hidden2" ] ); t( "value attribute", "input[value=Test]", [ "text1", "text2" ] ); assert.deepEqual( Sizzle( "input[data-comma='0,1']" ), q( "el12087" ), "Without context, single-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma=\"0,1\"]" ), q( "el12087" ), "Without context, double-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma='0,1']", document.getElementById( "t12087" ) ), q( "el12087" ), "With context, single-quoted attribute containing ','" ); assert.deepEqual( Sizzle( "input[data-comma=\"0,1\"]", document.getElementById( "t12087" ) ), q( "el12087" ), "With context, double-quoted attribute containing ','" ); }); QUnit.test("attributes - does not equal", function( assert ) { assert.expect( 2 ); t( "string", "#ap a[hreflang!='en']", [ "google", "groups", "anchor1" ] ); t( "empty string", "#select1 option[value!='']", [ "option1b", "option1c", "option1d" ] ); }); QUnit.test("attributes - starts with", function( assert ) { assert.expect( 4 ); // Support: IE<8 // There is apparently no way to bypass interpolation of the *originally-defined* href attribute document.getElementById("anchor2").href = "#2"; t( "string (whitespace ignored)", "a[href ^= 'http://www']", [ "google", "yahoo" ] ); t( "href starts with hash", "p a[href^='#']", [ "anchor2" ] ); t( "string containing '['", "input[name^='foo[']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name^='foo[bar]']", [ "hidden2" ] ); }); QUnit.test("attributes - contains", function( assert ) { assert.expect( 4 ); t( "string (whitespace ignored)", "a[href *= 'google']", [ "google", "groups" ] ); t( "string starting with '[' ... ']'", "input[name*='[bar]']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name*='foo[bar]']", [ "hidden2" ] ); t( "href contains hash", "p a[href*='#']", [ "simon1", "anchor2" ] ); }); QUnit.test("attributes - ends with", function( assert ) { assert.expect( 4 ); t( "string (whitespace ignored)", "a[href $= 'org/']", [ "mark" ] ); t( "string ending with ']'", "input[name$='bar]']", [ "hidden2" ] ); t( "string like '[' ... ']'", "input[name$='[bar]']", [ "hidden2" ] ); t( "string containing '[' ... ']'", "input[name$='foo[bar]']", [ "hidden2" ] ); }); QUnit.test("attributes - whitespace list includes", function( assert ) { assert.expect( 3 ); t( "string found at the beginning", "input[data-15233~='foo']", [ "t15233-single", "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); t( "string found in the middle", "input[data-15233~='bar']", [ "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); t( "string found at the end", "input[data-15233~='baz']", [ "t15233-triple" ] ); }); QUnit.test("attributes - hyphen-prefix matches", function( assert ) { assert.expect( 3 ); t( "string", "#names-group span[id|='name']", [ "name-is-example", "name-is-div" ] ); t( "string containing hyphen", "#names-group span[id|='name-is']", [ "name-is-example", "name-is-div" ] ); t( "string ending with hyphen", "#names-group span[id|='name-is-']", [] ); }); QUnit.test("attributes - special characters", function( assert ) { assert.expect( 13 ); var attrbad, div = document.createElement( "div" ); // #3279 div.innerHTML = "<div id='foo' xml:test='something'></div>"; assert.deepEqual( Sizzle( "[xml\\:test]", div ), [ div.firstChild ], "attribute name containing colon" ); // Make sure attribute value quoting works correctly. See jQuery #6093; #6428; #13894 // Use seeded results to bypass querySelectorAll optimizations attrbad = jQuery( "<input type='hidden' id='attrbad_space' name='foo bar'/>" + "<input type='hidden' id='attrbad_dot' value='2' name='foo.baz'/>" + "<input type='hidden' id='attrbad_brackets' value='2' name='foo[baz]'/>" + "<input type='hidden' id='attrbad_injection' data-attr='foo_baz&#39;]'/>" + "<input type='hidden' id='attrbad_quote' data-attr='&#39;'/>" + "<input type='hidden' id='attrbad_backslash' data-attr='&#92;'/>" + "<input type='hidden' id='attrbad_backslash_quote' data-attr='&#92;&#39;'/>" + "<input type='hidden' id='attrbad_backslash_backslash' data-attr='&#92;&#92;'/>" + "<input type='hidden' id='attrbad_unicode' data-attr='&#x4e00;'/>" ).appendTo("#qunit-fixture").get(); assert.deepEqual( Sizzle( "input[name=foo\\ bar]", null, null, attrbad ), q( "attrbad_space" ), "identifier containing space" ); assert.deepEqual( Sizzle( "input[name=foo\\.baz]", null, null, attrbad ), q( "attrbad_dot" ), "identifier containing dot" ); assert.deepEqual( Sizzle( "input[name=foo\\[baz\\]]", null, null, attrbad ), q( "attrbad_brackets" ), "identifier containing brackets" ); assert.deepEqual( Sizzle( "input[data-attr='foo_baz\\']']", null, null, attrbad ), q( "attrbad_injection" ), "string containing quote and right bracket" ); assert.deepEqual( Sizzle( "input[data-attr='\\'']", null, null, attrbad ), q( "attrbad_quote" ), "string containing quote" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\']", null, null, attrbad ), q( "attrbad_backslash" ), "string containing backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\\\'']", null, null, attrbad ), q( "attrbad_backslash_quote" ), "string containing backslash and quote" ); assert.deepEqual( Sizzle( "input[data-attr='\\\\\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing adjacent backslashes" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C \\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape-with-trailing-space backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\5C\t\\\\']", null, null, attrbad ), q( "attrbad_backslash_backslash" ), "string containing numeric-escape-with-trailing-tab backslash and backslash" ); assert.deepEqual( Sizzle( "input[data-attr='\\04e00']", null, null, attrbad ), q( "attrbad_unicode" ), "Long numeric escape (BMP)" ); document.getElementById( "attrbad_unicode" ).setAttribute( "data-attr", "\uD834\uDF06A" ); // It was too much code to fix Safari 5.x Supplemental Plane crashes (see ba5f09fa404379a87370ec905ffa47f8ac40aaa3) // assert.deepEqual( Sizzle( "input[data-attr='\\01D306A']", null, null, attrbad ), // q( "attrbad_unicode" ), // "Long numeric escape (non-BMP)" ); }); QUnit.test("attributes - other", function( assert ) { assert.expect( 7 ); var div = document.getElementById( "foo" ); t( "Selector list with multiple quoted attribute-equals", "#form input[type='radio'], #form input[type='hidden']", [ "radio1", "radio2", "hidden1" ] ); t( "Selector list with differently-quoted attribute-equals", "#form input[type='radio'], #form input[type=\"hidden\"]", [ "radio1", "radio2", "hidden1" ] ); t( "Selector list with quoted and unquoted attribute-equals", "#form input[type='radio'], #form input[type=hidden]", [ "radio1", "radio2", "hidden1" ] ); t( "attribute name is Object.prototype property \"constructor\" (negative)", "[constructor]", [] ); t( "attribute name is Gecko Object.prototype property \"watch\" (negative)", "[watch]", [] ); div.setAttribute( "constructor", "foo" ); div.setAttribute( "watch", "bar" ); t( "attribute name is Object.prototype property \"constructor\"", "[constructor='foo']", [ "foo" ] ); t( "attribute name is Gecko Object.prototype property \"watch\"", "[watch='bar']", [ "foo" ] ); }); QUnit.test("pseudo - (parent|empty)", function( assert ) { assert.expect( 3 ); t( "Empty", "#qunit-fixture ul:empty", ["firstUL"] ); t( "Empty with comment node", "#qunit-fixture ol:empty", ["empty"] ); t( "Is A Parent", "#qunit-fixture p:parent", ["firstp","ap","sndp","en","sap","first"] ); }); QUnit.test("pseudo - (first|last|only)-(child|of-type)", function( assert ) { assert.expect( 12 ); t( "First Child", "#qunit-fixture p:first-child", ["firstp","sndp"] ); t( "First Child (leading id)", "#qunit-fixture p:first-child", ["firstp","sndp"] ); t( "First Child (leading class)", ".nothiddendiv div:first-child", ["nothiddendivchild"] ); t( "First Child (case-insensitive)", "#qunit-fixture p:FIRST-CHILD", ["firstp","sndp"] ); t( "Last Child", "#qunit-fixture p:last-child", ["sap"] ); t( "Last Child (leading id)", "#qunit-fixture a:last-child", ["simon1","anchor1","mark","yahoo","anchor2","simon","liveLink1","liveLink2"] ); t( "Only Child", "#qunit-fixture a:only-child", ["simon1","anchor1","yahoo","anchor2","liveLink1","liveLink2"] ); t( "First-of-type", "#qunit-fixture > p:first-of-type", ["firstp"] ); t( "Last-of-type", "#qunit-fixture > p:last-of-type", ["first"] ); t( "Only-of-type", "#qunit-fixture > :only-of-type", ["name+value", "firstUL", "empty", "floatTest", "iframe", "table", "last"] ); // Verify that the child position isn't being cached improperly var secondChildren = jQuery("p:nth-child(2)").before("<div></div>"); t( "No longer second child", "p:nth-child(2)", [] ); secondChildren.prev().remove(); t( "Restored second child", "p:nth-child(2)", ["ap","en"] ); }); QUnit.test("pseudo - nth-child", function( assert ) { assert.expect( 30 ); t( "Nth-child", "p:nth-child(1)", ["firstp","sndp"] ); t( "Nth-child (with whitespace)", "p:nth-child( 1 )", ["firstp","sndp"] ); t( "Nth-child (case-insensitive)", "#form select:first option:NTH-child(3)", ["option1c"] ); t( "Not nth-child", "#qunit-fixture p:not(:nth-child(1))", ["ap","en","sap","first"] ); t( "Nth-child(2)", "#qunit-fixture form#form > *:nth-child(2)", ["text1"] ); t( "Nth-child(2)", "#qunit-fixture form#form > :nth-child(2)", ["text1"] ); t( "Nth-child(-1)", "#form select:first option:nth-child(-1)", [] ); t( "Nth-child(3)", "#form select:first option:nth-child(3)", ["option1c"] ); t( "Nth-child(0n+3)", "#form select:first option:nth-child(0n+3)", ["option1c"] ); t( "Nth-child(1n+0)", "#form select:first option:nth-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(1n)", "#form select:first option:nth-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(n)", "#form select:first option:nth-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-child(even)", "#form select:first option:nth-child(even)", ["option1b", "option1d"] ); t( "Nth-child(odd)", "#form select:first option:nth-child(odd)", ["option1a", "option1c"] ); t( "Nth-child(2n)", "#form select:first option:nth-child(2n)", ["option1b", "option1d"] ); t( "Nth-child(2n+1)", "#form select:first option:nth-child(2n+1)", ["option1a", "option1c"] ); t( "Nth-child(2n + 1)", "#form select:first option:nth-child(2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(+2n + 1)", "#form select:first option:nth-child(+2n + 1)", ["option1a", "option1c"] ); t( "Nth-child(3n)", "#form select:first option:nth-child(3n)", ["option1c"] ); t( "Nth-child(3n+1)", "#form select:first option:nth-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-child(3n+2)", "#form select:first option:nth-child(3n+2)", ["option1b"] ); t( "Nth-child(3n+3)", "#form select:first option:nth-child(3n+3)", ["option1c"] ); t( "Nth-child(3n-1)", "#form select:first option:nth-child(3n-1)", ["option1b"] ); t( "Nth-child(3n-2)", "#form select:first option:nth-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-child(3n-3)", "#form select:first option:nth-child(3n-3)", ["option1c"] ); t( "Nth-child(3n+0)", "#form select:first option:nth-child(3n+0)", ["option1c"] ); t( "Nth-child(-1n+3)", "#form select:first option:nth-child(-1n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-n+3)", "#form select:first option:nth-child(-n+3)", ["option1a", "option1b", "option1c"] ); t( "Nth-child(-1n + 3)", "#form select:first option:nth-child(-1n + 3)", ["option1a", "option1b", "option1c"] ); assert.deepEqual( Sizzle( ":nth-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-child" ); }); QUnit.test("pseudo - nth-last-child", function( assert ) { assert.expect( 30 ); jQuery( "#qunit-fixture" ).append( "<form id='nth-last-child-form'/><i/><i/><i/><i/>" ); t( "Nth-last-child", "form:nth-last-child(5)", ["nth-last-child-form"] ); t( "Nth-last-child (with whitespace)", "form:nth-last-child( 5 )", ["nth-last-child-form"] ); t( "Nth-last-child (case-insensitive)", "#form select:first option:NTH-last-child(3)", ["option1b"] ); t( "Not nth-last-child", "#qunit-fixture p:not(:nth-last-child(1))", ["firstp", "ap", "sndp", "en", "first"] ); t( "Nth-last-child(-1)", "#form select:first option:nth-last-child(-1)", [] ); t( "Nth-last-child(3)", "#form select:first :nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first *:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(3)", "#form select:first option:nth-last-child(3)", ["option1b"] ); t( "Nth-last-child(0n+3)", "#form select:first option:nth-last-child(0n+3)", ["option1b"] ); t( "Nth-last-child(1n+0)", "#form select:first option:nth-last-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(1n)", "#form select:first option:nth-last-child(1n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(n)", "#form select:first option:nth-last-child(n)", ["option1a", "option1b", "option1c", "option1d"] ); t( "Nth-last-child(even)", "#form select:first option:nth-last-child(even)", ["option1a", "option1c"] ); t( "Nth-last-child(odd)", "#form select:first option:nth-last-child(odd)", ["option1b", "option1d"] ); t( "Nth-last-child(2n)", "#form select:first option:nth-last-child(2n)", ["option1a", "option1c"] ); t( "Nth-last-child(2n+1)", "#form select:first option:nth-last-child(2n+1)", ["option1b", "option1d"] ); t( "Nth-last-child(2n + 1)", "#form select:first option:nth-last-child(2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(+2n + 1)", "#form select:first option:nth-last-child(+2n + 1)", ["option1b", "option1d"] ); t( "Nth-last-child(3n)", "#form select:first option:nth-last-child(3n)", ["option1b"] ); t( "Nth-last-child(3n+1)", "#form select:first option:nth-last-child(3n+1)", ["option1a", "option1d"] ); t( "Nth-last-child(3n+2)", "#form select:first option:nth-last-child(3n+2)", ["option1c"] ); t( "Nth-last-child(3n+3)", "#form select:first option:nth-last-child(3n+3)", ["option1b"] ); t( "Nth-last-child(3n-1)", "#form select:first option:nth-last-child(3n-1)", ["option1c"] ); t( "Nth-last-child(3n-2)", "#form select:first option:nth-last-child(3n-2)", ["option1a", "option1d"] ); t( "Nth-last-child(3n-3)", "#form select:first option:nth-last-child(3n-3)", ["option1b"] ); t( "Nth-last-child(3n+0)", "#form select:first option:nth-last-child(3n+0)", ["option1b"] ); t( "Nth-last-child(-1n+3)", "#form select:first option:nth-last-child(-1n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-n+3)", "#form select:first option:nth-last-child(-n+3)", ["option1b", "option1c", "option1d"] ); t( "Nth-last-child(-1n + 3)", "#form select:first option:nth-last-child(-1n + 3)", ["option1b", "option1c", "option1d"] ); QUnit.deepEqual( Sizzle( ":nth-last-child(n)", null, null, [ document.createElement("a") ].concat( q("ap") ) ), q("ap"), "Seeded nth-last-child" ); }); QUnit.test("pseudo - nth-of-type", function( assert ) { assert.expect( 9 ); t( "Nth-of-type(-1)", ":nth-of-type(-1)", [] ); t( "Nth-of-type(3)", "#ap :nth-of-type(3)", ["mark"] ); t( "Nth-of-type(n)", "#ap :nth-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-of-type(0n+3)", "#ap :nth-of-type(0n+3)", ["mark"] ); t( "Nth-of-type(2n)", "#ap :nth-of-type(2n)", ["groups"] ); t( "Nth-of-type(even)", "#ap :nth-of-type(even)", ["groups"] ); t( "Nth-of-type(2n+1)", "#ap :nth-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(odd)", "#ap :nth-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-of-type(-n+2)", "#qunit-fixture > :nth-of-type(-n+2)", ["firstp", "ap", "foo", "nothiddendiv", "name+value", "firstUL", "empty", "form", "floatTest", "iframe", "lengthtest", "table", "last"] ); }); QUnit.test("pseudo - nth-last-of-type", function( assert ) { assert.expect( 9 ); t( "Nth-last-of-type(-1)", ":nth-last-of-type(-1)", [] ); t( "Nth-last-of-type(3)", "#ap :nth-last-of-type(3)", ["google"] ); t( "Nth-last-of-type(n)", "#ap :nth-last-of-type(n)", ["google", "groups", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(0n+3)", "#ap :nth-last-of-type(0n+3)", ["google"] ); t( "Nth-last-of-type(2n)", "#ap :nth-last-of-type(2n)", ["groups"] ); t( "Nth-last-of-type(even)", "#ap :nth-last-of-type(even)", ["groups"] ); t( "Nth-last-of-type(2n+1)", "#ap :nth-last-of-type(2n+1)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(odd)", "#ap :nth-last-of-type(odd)", ["google", "code1", "anchor1", "mark"] ); t( "Nth-last-of-type(-n+2)", "#qunit-fixture > :nth-last-of-type(-n+2)", ["ap", "name+value", "first", "firstUL", "empty", "floatTest", "iframe", "table", "testForm", "liveHandlerOrder", "disabled-tests", "siblingTest", "last"] ); }); QUnit.test("pseudo - has", function( assert ) { assert.expect( 3 ); t( "Basic test", "p:has(a)", ["firstp","ap","en","sap"] ); t( "Basic test (irrelevant whitespace)", "p:has( a )", ["firstp","ap","en","sap"] ); t( "Nested with overlapping candidates", "#qunit-fixture div:has(div:has(div:not([id])))", [ "moretests", "t2037" ] ); }); +QUnit.test("pseudo - contains", function( assert ) { + assert.expect( 9 ); + + var gh335 = document.getElementById( "qunit-fixture" ).appendChild( + document.createElement( "mark" ) ); + gh335.id = "gh-335"; + gh335.appendChild( document.createTextNode( "raw line 1\nline 2" ) ); + + assert.ok( Sizzle("a:contains('')").length, "empty string" ); + t( "unquoted argument", "a:contains(Google)", ["google","groups"] ); + t( "unquoted argument with whitespace", "a:contains(Google Groups)", ["groups"] ); + t( "quoted argument with whitespace and parentheses", + "a:contains('Google Groups (Link)')", ["groups"] ); + t( "quoted argument with double quotes and parentheses", + "a:contains(\"(Link)\")", ["groups"] ); + t( "unquoted argument with whitespace and paired parentheses", + "a:contains(Google Groups (Link))", ["groups"] ); + t( "unquoted argument with paired parentheses", "a:contains((Link))", ["groups"] ); + t( "quoted argument with CSS escapes", + "span:contains(\"\\\"'\\53F0 \\5317 Ta\\301 ibe\\30C i\")", + ["utf8class1"] ); + + t( "collapsed whitespace", "mark:contains('line 1\\A line')", ["gh-335"] ); +}); + QUnit.test("pseudo - misc", function( assert ) { - assert.expect( 40 ); + assert.expect( 32 ); var select, tmp, input; jQuery( "<h1 id='h1'/><h2 id='h2'/><h2 id='h2-2'/>" ).prependTo( "#qunit-fixture" ); t( "Headers", "#qunit-fixture :header", ["h1", "h2", "h2-2"] ); t( "Headers(case-insensitive)", "#qunit-fixture :Header", ["h1", "h2", "h2-2"] ); t( "Multiple matches with the same context (cache check)", "#form select:has(option:first-child:contains('o'))", ["select1", "select2", "select3", "select4"] ); assert.ok( Sizzle("#qunit-fixture :not(:has(:has(*)))").length, "All not grandparents" ); select = document.getElementById("select1"); assert.ok( Sizzle.matchesSelector( select, ":has(option)" ), "Has Option Matches" ); - assert.ok( Sizzle("a:contains('')").length, "Empty string contains" ); - t( "Text Contains", "a:contains(Google)", ["google","groups"] ); - t( "Text Contains", "a:contains(Google Groups)", ["groups"] ); - - t( "Text Contains", "a:contains('Google Groups (Link)')", ["groups"] ); - t( "Text Contains", "a:contains(\"(Link)\")", ["groups"] ); - t( "Text Contains", "a:contains(Google Groups (Link))", ["groups"] ); - t( "Text Contains", "a:contains((Link))", ["groups"] ); - - t( "Contains with CSS escapes", "span:contains(\"\\\"'\\53F0 \\5317 Ta\\301 ibe\\30C i\")", - ["utf8class1"] ); - tmp = document.createElement("div"); tmp.id = "tmp_input"; document.body.appendChild( tmp ); jQuery.each( [ "button", "submit", "reset" ], function( i, type ) { var els = jQuery( "<input id='input_%' type='%'/><button id='button_%' type='%'>test</button>" .replace( /%/g, type ) ).appendTo( tmp ); t( "Input Buttons :" + type, "#tmp_input :" + type, [ "input_" + type, "button_" + type ] ); assert.ok( Sizzle.matchesSelector( els[0], ":" + type ), "Input Matches :" + type ); assert.ok( Sizzle.matchesSelector( els[1], ":" + type ), "Button Matches :" + type ); }); document.body.removeChild( tmp ); // Recreate tmp tmp = document.createElement("div"); tmp.id = "tmp_input"; tmp.innerHTML = "<span>Hello I am focusable.</span>"; // Setting tabIndex should make the element focusable // http://dev.w3.org/html5/spec/single-page.html#focus-management document.body.appendChild( tmp ); tmp.tabIndex = 0; tmp.focus(); if ( document.activeElement !== tmp || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("div:focus").length) ) { assert.ok( true, "The div was not focused. Skip checking the :focus match." ); assert.ok( true, "The div was not focused. Skip checking the :focus match." ); } else { t( "tabIndex element focused", ":focus", [ "tmp_input" ] ); assert.ok( Sizzle.matchesSelector( tmp, ":focus" ), ":focus matches tabIndex div" ); } // Blur tmp tmp.blur(); document.body.focus(); assert.ok( !Sizzle.matchesSelector( tmp, ":focus" ), ":focus doesn't match tabIndex div" ); document.body.removeChild( tmp ); // Input focus/active input = document.createElement("input"); input.type = "text"; input.id = "focus-input"; document.body.appendChild( input ); input.focus(); // Inputs can't be focused unless the document has focus if ( document.activeElement !== input || (document.hasFocus && !document.hasFocus()) || (document.querySelectorAll && !document.querySelectorAll("input:focus").length) ) { assert.ok( true, "The input was not focused. Skip checking the :focus match." ); assert.ok( true, "The input was not focused. Skip checking the :focus match." ); } else { t( "Element focused", "input:focus", [ "focus-input" ] ); assert.ok( Sizzle.matchesSelector( input, ":focus" ), ":focus matches" ); } input.blur(); // When IE is out of focus, blur does not work. Force it here. if ( document.activeElement === input ) { document.body.focus(); } assert.ok( !Sizzle.matchesSelector( input, ":focus" ), ":focus doesn't match" ); document.body.removeChild( input ); assert.deepEqual( Sizzle( "[id='select1'] *:not(:last-child), [id='select2'] *:not(:last-child)", q("qunit-fixture")[0] ), q( "option1a", "option1b", "option1c", "option2a", "option2b", "option2c" ), "caching system tolerates recursive selection" ); // Tokenization edge cases t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code)", ["ap"] ); t( "Sequential pseudos", "#qunit-fixture p:has(:contains(mark)):has(code):contains(This link)", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo argument containing ')'", "p:has(>a.GROUPS[src!=')'])", ["ap"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=\\)]", ["sndp"] ); t( "Pseudo followed by token containing ')'", "p:contains(id=\"foo\")[id!=')']", ["sndp"] ); t( "Multi-pseudo", "#ap:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional", "#ap:gt(0), #ap:lt(1)", ["ap"] ); t( "Multi-pseudo with leading nonexistent id", "#nonexistent:has(*), #ap:has(*)", ["ap"] ); t( "Multi-positional with leading nonexistent id", "#nonexistent:gt(0), #ap:lt(1)", ["ap"] ); t( "Tokenization stressor", "a[class*=blog]:not(:has(*, :contains(!)), :contains(!)), br:contains(]), p:contains(]), :not(:empty):not(:parent)", ["ap", "mark","yahoo","simon"] ); }); QUnit.test("pseudo - :not", function( assert ) { assert.expect( 43 ); t( "Not", "a.blog:not(.link)", ["mark"] ); t( ":not() with :first", "#foo p:not(:first) .link", ["simon"] ); t( "Not - multiple", "#form option:not(:contains(Nothing),#option1b,:selected)", ["option1c", "option1d", "option2b", "option2c", "option3d", "option3e", "option4e", "option5b", "option5c"] ); t( "Not - recursive", "#form option:not(:not(:selected))[id^='option3']", [ "option3b", "option3c"] ); t( ":not() failing interior", "#qunit-fixture p:not(.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p.foo)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(div#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not() failing interior", "#qunit-fixture p:not(p#blargh)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( a )", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not( p )", [] ); t( ":not Multiple", "#qunit-fixture p:not(a, b)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "#qunit-fixture p:not(a, b, div)", ["firstp","ap","sndp","en","sap","first"] ); t( ":not Multiple", "p:not(p)", [] ); t( ":not Multiple", "p:not(a,p)", [] ); t( ":not Multiple", "p:not(p,a)", [] ); t( ":not Multiple", "p:not(a,p,b)", [] ); t( ":not Multiple", ":input:not(:image,:input,:submit)", [] ); t( ":not Multiple", "#qunit-fixture p:not(:has(a), :nth-child(1))", ["first"] ); t( "No element not selector", ".container div:not(.excluded) div", [] ); t( ":not() Existing attribute", "#form select:not([multiple])", ["select1", "select2", "select5"]); t( ":not() Equals attribute", "#form select:not([name=select1])", ["select2", "select3", "select4","select5"]); t( ":not() Equals quoted attribute", "#form select:not([name='select1'])", ["select2", "select3", "select4", "select5"]); t( ":not() Multiple Class", "#foo a:not(.blog)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.link)", ["yahoo", "anchor2"] ); t( ":not() Multiple Class", "#foo a:not(.blog.link)", ["yahoo", "anchor2"] ); t( ":not chaining (compound)", "#qunit-fixture div[id]:not(:has(div, span)):not(:has(*))", ["nothiddendivchild", "divWithNoTabIndex"] ); t( ":not chaining (with attribute)", "#qunit-fixture form[id]:not([action$='formaction']):not(:button)", ["lengthtest", "name-tests", "testForm", "disabled-tests"] ); t( ":not chaining (colon in attribute)", "#qunit-fixture form[id]:not([action='form:action']):not(:button)", ["form", "lengthtest", "name-tests", "testForm", "disabled-tests"] ); t( ":not chaining (colon in attribute and nested chaining)", "#qunit-fixture form[id]:not([action='form:action']:button):not(:input)", ["form", "lengthtest", "name-tests", "testForm", "disabled-tests"] ); t( ":not chaining", "#form select:not(.select1):contains(Nothing) > option:not(option)", [] ); t( "positional :not()", "#foo p:not(:last)", ["sndp", "en"] ); t( "positional :not() prefix", "#foo p:not(:last) a", ["yahoo"] ); t( "compound positional :not()", "#foo p:not(:first, :last)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :even)", ["en"] ); t( "compound positional :not()", "#foo p:not(:first, :odd)", ["sap"] ); t( "reordered compound positional :not()", "#foo p:not(:odd, :first)", ["sap"] ); t( "positional :not() with pre-filter", "#foo p:not([id]:first)", ["en", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[id])", ["en", "sap"] ); t( "positional :not() with pre-filter", "#foo p:not([lang]:first)", ["sndp", "sap"] ); t( "positional :not() with post-filter", "#foo p:not(:first[lang])", ["sndp", "en", "sap"] ); }); QUnit.test("pseudo - position", function( assert ) { assert.expect( 34 ); t( "First element", "#qunit-fixture p:first", ["firstp"] ); t( "First element(case-insensitive)", "#qunit-fixture p:fiRst", ["firstp"] ); t( "nth Element", "#qunit-fixture p:nth(1)", ["ap"] ); t( "First Element", "#qunit-fixture p:first", ["firstp"] ); t( "Last Element", "p:last", ["first"] ); t( "Even Elements", "#qunit-fixture p:even", ["firstp","sndp","sap"] ); t( "Odd Elements", "#qunit-fixture p:odd", ["ap","en","first"] ); t( "Position Equals", "#qunit-fixture p:eq(1)", ["ap"] ); t( "Position Equals (negative)", "#qunit-fixture p:eq(-1)", ["first"] ); t( "Position Greater Than", "#qunit-fixture p:gt(0)", ["ap","sndp","en","sap","first"] ); t( "Position Less Than", "#qunit-fixture p:lt(3)", ["firstp","ap","sndp"] ); t( "Position Less Than Big Number", "#qunit-fixture p:lt(9007199254740991)", ["firstp","ap","sndp","en","sap","first"] ); t( "Check position filtering", "div#nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div#nothiddendiv:not(:gt(0))", ["nothiddendiv"] ); t( "Check position filtering", "#foo > :not(:first)", ["en", "sap"] ); t( "Check position filtering", "#qunit-fixture select > :not(:gt(2))", ["option1a", "option1b", "option1c"] ); t( "Check position filtering", "#qunit-fixture select:lt(2) :not(:first)", ["option1b", "option1c", "option1d", "option2a", "option2b", "option2c", "option2d"] ); t( "Check position filtering", "div.nothiddendiv:eq(0)", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:last", ["nothiddendiv"] ); t( "Check position filtering", "div.nothiddendiv:not(:lt(0))", ["nothiddendiv"] ); t( "Check element position", "#qunit-fixture div div:eq(0)", ["nothiddendivchild"] ); t( "Check element position", "#select1 option:eq(3)", ["option1d"] ); t( "Check element position", "#qunit-fixture div div:eq(10)", ["names-group"] ); t( "Check element position", "#qunit-fixture div div:first", ["nothiddendivchild"] ); t( "Check element position", "#qunit-fixture div > div:first", ["nothiddendivchild"] ); t( "Check element position", "#qunit-fixture div:first a:first", ["yahoo"] ); t( "Check element position", "#qunit-fixture div:first > p:first", ["sndp"] ); t( "Check element position", "div#nothiddendiv:first > div:first", ["nothiddendivchild"] ); t( "Chained pseudo after a pos pseudo", "#listWithTabIndex li:eq(0):contains(Rice)", ["foodWithNegativeTabIndex"] ); t( "Check sort order with POS and comma", "#qunit-fixture em>em>em>em:first-child,div>em:first", ["siblingfirst", "siblinggreatgrandchild"] ); t( "Isolated position", "#qunit-fixture :last", ["last"] ); assert.deepEqual( Sizzle( "*:lt(2) + *", null, [], Sizzle("#qunit-fixture > p") ), q("ap"), "Seeded pos with trailing relative" ); // jQuery #12526 var context = jQuery("#qunit-fixture").append("<div id='jquery12526'></div>")[0]; assert.deepEqual( Sizzle( ":last", context ), q("jquery12526"), "Post-manipulation positional" ); }); QUnit.test("pseudo - form", function( assert ) { assert.expect( 10 ); var extraTexts = jQuery("<input id=\"impliedText\"/><input id=\"capitalText\" type=\"TEXT\">").appendTo("#form"); t( "Form element :input", "#form :input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "search", "button", "area1", "select1", "select2", "select3", "select4", "select5", "impliedText", "capitalText"] ); t( "Form element :radio", "#form :radio", ["radio1", "radio2"] ); t( "Form element :checkbox", "#form :checkbox", ["check1", "check2"] ); t( "Form element :text", "#form :text", ["text1", "text2", "hidden2", "name", "impliedText", "capitalText"] ); t( "Form element :radio:checked", "#form :radio:checked", ["radio2"] ); t( "Form element :checkbox:checked", "#form :checkbox:checked", ["check1"] ); t( "Form element :radio:checked, :checkbox:checked", "#form :radio:checked, #form :checkbox:checked", ["radio2", "check1"] ); t( "Selected option element", "#form option:selected", [ "option1a", "option2d", "option3b", "option3c", "option4b", "option4c", "option4d", "option5a" ] ); t( "Selected option elements are also :checked", "#form option:checked", [ "option1a", "option2d", "option3b", "option3c", "option4b", "option4c", "option4d", "option5a" ] ); t( "Hidden inputs are still :enabled", "#hidden1:enabled", [ "hidden1" ] ); extraTexts.remove(); }); QUnit.test("pseudo - :(dis|en)abled, explicitly disabled", function( assert ) { assert.expect( 2 ); // Set a meaningless disabled property on a common ancestor var container = document.getElementById( "disabled-tests" ); container.disabled = true; // Support: IE 6 - 11 // Unset the property where it is not meaningless if ( document.getElementById( "enabled-input" ).isDisabled ) { container.disabled = undefined; } t( "Explicitly disabled elements", "#enabled-fieldset :disabled", [ "disabled-input", "disabled-textarea", "disabled-button", "disabled-select", "disabled-optgroup", "disabled-option" ] ); t( "Enabled elements", "#enabled-fieldset :enabled", [ "enabled-input", "enabled-textarea", "enabled-button", "enabled-select", "enabled-optgroup", "enabled-option" ] ); }); QUnit.test("pseudo - :(dis|en)abled, optgroup and option", function( assert ) { assert.expect( 2 ); t( ":disabled", "#disabled-select-inherit :disabled, #enabled-select-inherit :disabled", [ "disabled-optgroup-inherit", "disabled-optgroup-option", "en_disabled-optgroup-inherit", "en_disabled-optgroup-option" ] ); t( ":enabled", "#disabled-select-inherit :enabled, #enabled-select-inherit :enabled", [ "enabled-optgroup-inherit", "enabled-optgroup-option", "enabled-select-option" ] ); }); // Support: PhantomJS // fieldsetElement.disabled is undefined if ( jQuery("<fieldset disabled='disabled'/>")[0].disabled ) { QUnit.test("pseudo - fieldset:(dis|en)abled", function() { t( "Disabled fieldset", "fieldset:disabled", [ "disabled-fieldset" ] ); t( "Enabled fieldset", "fieldset:enabled", [ "enabled-fieldset" ] ); }); QUnit.test("pseudo - :disabled by ancestry", function( assert ) { assert.expect( 1 ); // Don't test for presence of select // IE6 doesn't visibly or functionally disable them when the fieldset is disabled t( "Inputs inherit disabled from fieldset", "#disabled-fieldset :disabled", [ "disabled-fieldset-input", "disabled-fieldset-textarea", "disabled-fieldset-button" ] ); }); } QUnit.test("pseudo - :target and :root", function( assert ) { assert.expect( 2 ); // Target var oldHash, $link = jQuery("<a/>").attr({ href: "#", id: "new-link" }).appendTo("#qunit-fixture"); oldHash = window.location.hash; window.location.hash = "new-link"; t( ":target", ":target", ["new-link"] ); $link.remove(); window.location.hash = oldHash; // Root assert.equal( Sizzle(":root")[0], document.documentElement, ":root selector" ); }); QUnit.test("pseudo - :lang", function( assert ) { assert.expect( 105 ); var docElem = document.documentElement, docXmlLang = docElem.getAttribute("xml:lang"), docLang = docElem.lang, foo = document.getElementById("foo"), anchor = document.getElementById("anchor2"), xml = createWithFriesXML(), testLang = function( text, elem, container, lang, extra ) { var message, full = lang + "-" + extra; message = "lang=" + lang + " " + text; container.setAttribute( container.ownerDocument.documentElement.nodeName === "HTML" ? "lang" : "xml:lang", lang ); assertMatch( message, elem, ":lang(" + lang + ")" ); assertMatch( message, elem, ":lang(" + mixCase(lang) + ")" ); assertNoMatch( message, elem, ":lang(" + full + ")" ); assertNoMatch( message, elem, ":lang(" + mixCase(full) + ")" ); assertNoMatch( message, elem, ":lang(" + lang + "-)" ); assertNoMatch( message, elem, ":lang(" + full + "-)" ); assertNoMatch( message, elem, ":lang(" + lang + "glish)" ); assertNoMatch( message, elem, ":lang(" + full + "glish)" ); message = "lang=" + full + " " + text; container.setAttribute( container.ownerDocument.documentElement.nodeName === "HTML" ? "lang" : "xml:lang", full ); assertMatch( message, elem, ":lang(" + lang + ")" ); assertMatch( message, elem, ":lang(" + mixCase(lang) + ")" ); assertMatch( message, elem, ":lang(" + full + ")" ); assertMatch( message, elem, ":lang(" + mixCase(full) + ")" ); assertNoMatch( message, elem, ":lang(" + lang + "-)" ); assertNoMatch( message, elem, ":lang(" + full + "-)" ); assertNoMatch( message, elem, ":lang(" + lang + "glish)" ); assertNoMatch( message, elem, ":lang(" + full + "glish)" ); }, mixCase = function( str ) { var ret = str.split(""), i = ret.length; while ( i-- ) { if ( i & 1 ) { ret[i] = ret[i].toUpperCase(); } } return ret.join(""); }, assertMatch = function( text, elem, selector ) { assert.ok( Sizzle.matchesSelector( elem, selector ), text + " match " + selector ); }, assertNoMatch = function( text, elem, selector ) { assert.ok( !Sizzle.matchesSelector( elem, selector ), text + " fail " + selector ); }; // Prefixing and inheritance assert.ok( Sizzle.matchesSelector( docElem, ":lang(" + docElem.lang + ")" ), "starting :lang" ); testLang( "document", anchor, docElem, "en", "us" ); testLang( "grandparent", anchor, anchor.parentNode.parentNode, "yue", "hk" ); assert.ok( !Sizzle.matchesSelector( anchor, ":lang(en), :lang(en-us)" ), ":lang does not look above an ancestor with specified lang" ); testLang( "self", anchor, anchor, "es", "419" ); assert.ok( !Sizzle.matchesSelector( anchor, ":lang(en), :lang(en-us), :lang(yue), :lang(yue-hk)" ), ":lang does not look above self with specified lang" ); // Searching by language tag anchor.parentNode.parentNode.lang = "arab"; anchor.parentNode.lang = anchor.parentNode.id = "ara-sa"; anchor.lang = "ara"; assert.deepEqual( Sizzle( ":lang(ara)", foo ), [ anchor.parentNode, anchor ], "Find by :lang" ); // Selector validity anchor.parentNode.lang = "ara"; anchor.lang = "ara\\b"; assert.deepEqual( Sizzle( ":lang(ara\\b)", foo ), [], ":lang respects backslashes" ); assert.deepEqual( Sizzle( ":lang(ara\\\\b)", foo ), [ anchor ], ":lang respects escaped backslashes" ); assert.throws(function() { Sizzle.call( null, "#qunit-fixture:lang(c++)" ); }, function( e ) { return e.message.indexOf("Syntax error") >= 0; }, ":lang value must be a valid identifier" ); // XML foo = jQuery( "response", xml )[0]; anchor = jQuery( "#seite1", xml )[0]; testLang( "XML document", anchor, xml.documentElement, "en", "us" ); testLang( "XML grandparent", anchor, foo, "yue", "hk" ); assert.ok( !Sizzle.matchesSelector( anchor, ":lang(en), :lang(en-us)" ), "XML :lang does not look above an ancestor with specified lang" ); testLang( "XML self", anchor, anchor, "es", "419" ); assert.ok( !Sizzle.matchesSelector( anchor, ":lang(en), :lang(en-us), :lang(yue), :lang(yue-hk)" ), "XML :lang does not look above self with specified lang" ); // Cleanup if ( docXmlLang == null ) { docElem.removeAttribute("xml:lang"); } else { docElem.setAttribute( "xml:lang", docXmlLang ); } docElem.lang = docLang; }); QUnit.test("context", function( assert ) { assert.expect( 21 ); var context, selector = ".blog", expected = q( "mark", "simon" ), iframe = document.getElementById( "iframe" ), iframeDoc = iframe.contentDocument || iframe.contentWindow.document; assert.deepEqual( Sizzle( selector, document ), expected, "explicit document context" ); assert.deepEqual( Sizzle( selector ), expected, "unspecified context becomes document" ); assert.deepEqual( Sizzle( selector, undefined ), expected, "undefined context becomes document" ); assert.deepEqual( Sizzle( selector, null ), expected, "null context becomes document" ); iframeDoc.open(); iframeDoc.write( "<body><p id='foo'>bar</p></body>" ); iframeDoc.close(); expected = [ iframeDoc.getElementById( "foo" ) ]; assert.deepEqual( Sizzle( "p", iframeDoc ), expected, "Other document context (simple)"); assert.deepEqual( Sizzle( "p:contains(ar)", iframeDoc ), expected, "Other document context (complex)"); assert.deepEqual( Sizzle( "span", iframeDoc ), [], "Other document context (simple, no results)"); assert.deepEqual( Sizzle( "* span", iframeDoc ), [], "Other document context (complex, no results)"); context = document.getElementById( "nothiddendiv" ); assert.deepEqual( Sizzle( "*", context ), q( "nothiddendivchild" ), "<div> context" ); assert.deepEqual( Sizzle( "* > *", context ), [], "<div> context (no results)" ); context.removeAttribute( "id" ); assert.deepEqual( Sizzle( "*", context ), q( "nothiddendivchild" ), "no-id element context" ); assert.deepEqual( Sizzle( "* > *", context ), [], "no-id element context (no results)" ); // Support: IE<8 only // ID attroperty is never really gone assert.strictEqual( context.getAttribute( "id" ) || "", "", "id not added by no-id selection" ); context = document.getElementById( "lengthtest" ); assert.deepEqual( Sizzle( "input", context ), q( "length", "idTest" ), "<form> context"); assert.deepEqual( Sizzle( "select", context ), [], "<form> context (no results)"); context = document.getElementById( "台北Táiběi" ); expected = q( "台北Táiběi-child" ); assert.deepEqual( Sizzle( "span[id]", context ), expected, "context with non-ASCII id"); assert.deepEqual( Sizzle( "#台北Táiběi span[id]", context.parentNode ), expected, "context with non-ASCII id selector prefix"); context = document.createDocumentFragment(); // Capture *independent* expected nodes before they're detached from the page expected = q( "siblingnext", "siblingspan" ); context.appendChild( document.getElementById( "siblingTest" ) ); assert.deepEqual( Sizzle( "em:nth-child(2)", context ), expected.slice( 0, 1 ), "DocumentFragment context" ); assert.deepEqual( Sizzle( "span", context ), expected.slice( 1 ), "DocumentFragment context by tag name" ); assert.deepEqual( Sizzle( "p", context ), [], "DocumentFragment context (no results)" ); assert.deepEqual( Sizzle( "em + :not(:has(*)):not(:empty), foo", context.firstChild ), expected.slice( 0, 1 ), "Non-qSA path correctly sets detached context for sibling selectors (jQuery #14351)" ); }); QUnit.test("caching", function( assert ) { assert.expect( 3 ); var sap = document.getElementById("sap"); Sizzle( ":not(code)", document.getElementById("ap") ); assert.deepEqual( Sizzle( ":not(code)", document.getElementById("foo") ), q( "sndp", "en", "yahoo", "sap", "anchor2", "simon" ), "Reusing selector with new context" ); t( "Deep ancestry caching in post-positional element matcher (jQuery #14657)", "#qunit-fixture a:lt(3):parent", [ "simon1", "google", "groups" ] ); sap.className = "original"; Sizzle( "#qunit-fixture:noQSA .original" ); document.getElementById("nothiddendiv").appendChild( sap.cloneNode( true ) ).className = "clone"; assert.equal( Sizzle( "#qunit-fixture:noQSA .clone [href*='2']" ).length, 1, "Cloning does not poison caches" );
jquery/sizzle
26a1f3f6f156cb687d0d7adc7bf79f0e5454811a
Misc: Update isXML to recognize HTML-embedded elements
diff --git a/dist/sizzle.js b/dist/sizzle.js index 5d234f0..150d90c 100644 --- a/dist/sizzle.js +++ b/dist/sizzle.js @@ -1,1077 +1,1081 @@ /*! * Sizzle CSS Selector Engine v2.3.4-pre * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * - * Date: 2018-11-04 + * Date: 2018-12-03 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, + rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; + var namespace = elem.namespaceURI, + docElem = (elem.ownerDocument || elem).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; diff --git a/dist/sizzle.min.js b/dist/sizzle.min.js index d884567..d4ea5ac 100644 --- a/dist/sizzle.min.js +++ b/dist/sizzle.min.js @@ -1,3 +1,3 @@ /*! Sizzle v2.3.4-pre | (c) JS Foundation and other contributors | js.foundation */ -!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=le(),D=le(),S=le(),A=le(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",z="[\\x20\\t\\r\\n\\f]",H="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+z+"*("+H+")(?:"+z+"*([*^$|!~]?=)"+z+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+H+"))|)"+z+"*\\]",F=":("+H+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(z+"+","g"),j=new RegExp("^"+z+"+|((?:^|[^\\\\])(?:\\\\.)*)"+z+"+$","g"),G=new RegExp("^"+z+"*,"+z+"*"),U=new RegExp("^"+z+"*([>+~]|"+z+")"+z+"*"),V=new RegExp(z+"|>"),X=new RegExp(F),J=new RegExp("^"+H+"$"),K={ID:new RegExp("^#("+H+")"),CLASS:new RegExp("^\\.("+H+")"),TAG:new RegExp("^("+H+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+z+"*(even|odd|(([+-]|)(\\d*)n|)"+z+"*(?:([+-]|)"+z+"*(\\d+)|))"+z+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+z+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+z+"*((?:-\\d)?\\d*)"+z+"*\\)|)(?=[^-]|$)","i")},Q=/^(?:input|select|textarea|button)$/i,W=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,ee=new RegExp("\\\\([\\da-f]{1,6}"+z+"?|("+z+")|.)","ig"),te=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},ne=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,re=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},ie=function(){d()},oe=ye(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function ue(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=Z.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(ne,re):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+me(h[l]);y=h.join(","),w=_.test(e)&&he(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function le(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ae(e){return e[b]=!0,e}function ce(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function se(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function fe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&oe(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function pe(e){return ae(function(t){return t=+t,ae(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function he(e){return e&&void 0!==e.getElementsByTagName&&e}n=ue.support={},o=ue.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},d=ue.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",ie,!1):i.attachEvent&&i.attachEvent("onunload",ie)),n.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ce(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Y.test(p.getElementsByClassName),n.getById=ce(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(ee,te);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(ee,te);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Y.test(p.querySelectorAll))&&(ce(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+z+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+z+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+z+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Y.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ce(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Y.test(h.compareDocumentPosition),v=t||Y.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return fe(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?fe(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},ue.matches=function(e,t){return ue(e,null,null,t)},ue.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return ue(t,p,null,[e]).length>0},ue.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},ue.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},ue.escape=function(e){return(e+"").replace(ne,re)},ue.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},ue.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=ue.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=ue.selectors={cacheLength:50,createPseudo:ae,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(ee,te),e[3]=(e[3]||e[4]||e[5]||"").replace(ee,te),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ue.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ue.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(ee,te).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+z+")"+e+"("+z+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ue.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||ue.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ae(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ae(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ae(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ae(function(e){return function(t){return ue(e,t).length>0}}),contains:ae(function(e){return e=e.replace(ee,te),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:ae(function(e){return J.test(e||"")||ue.error("unsupported lang: "+e),e=e.replace(ee,te).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return W.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:pe(function(){return[0]}),last:pe(function(e,t){return[t-1]}),eq:pe(function(e,t,n){return[n<0?n+t:n]}),even:pe(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:pe(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:pe(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:pe(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function ge(){}ge.prototype=r.filters=r.pseudos,r.setFilters=new ge,u=ue.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?ue.error(e):D(e,a).slice(0)};function me(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function ye(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function we(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function ve(e,t,n){for(var r=0,i=t.length;r<i;r++)ue(e,t[r],n);return n}function be(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function Ne(e,t,n,r,i,o){return r&&!r[b]&&(r=Ne(r)),i&&!i[b]&&(i=Ne(i,o)),ae(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||ve(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:be(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=be(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=be(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function xe(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=ye(function(e){return e===t},l,!0),f=ye(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[ye(we(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return Ne(a>1&&we(d),a>1&&me(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&xe(e.slice(a,i)),i<o&&xe(e=e.slice(i)),i<o&&me(e))}d.push(n)}return we(d)}function Ce(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=be(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&ue.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ae(o):o}l=ue.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=xe(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ce(i,r))).selector=e}return o},a=ue.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(ee,te),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(ee,te),_.test(a[0].type)&&he(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&me(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||_.test(e)&&he(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||se("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||se("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||se(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var Ee=e.Sizzle;ue.noConflict=function(){return e.Sizzle===ue&&(e.Sizzle=Ee),ue},"function"==typeof define&&define.amd?define(function(){return ue}):"undefined"!=typeof module&&module.exports?module.exports=ue:e.Sizzle=ue}(window); +!function(e){var t,n,r,i,o,u,l,a,c,s,f,d,p,h,g,m,y,w,v,b="sizzle"+1*new Date,N=e.document,x=0,C=0,E=ae(),D=ae(),S=ae(),A=ae(),T=function(e,t){return e===t&&(f=!0),0},L={}.hasOwnProperty,I=[],q=I.pop,B=I.push,R=I.push,$=I.slice,k=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",P="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",z="\\["+M+"*("+P+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+P+"))|)"+M+"*\\]",F=":("+P+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+z+")*)|.*)\\)|)",O=new RegExp(M+"+","g"),j=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),G=new RegExp("^"+M+"*,"+M+"*"),U=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),V=new RegExp(M+"|>"),X=new RegExp(F),J=new RegExp("^"+P+"$"),K={ID:new RegExp("^#("+P+")"),CLASS:new RegExp("^\\.("+P+")"),TAG:new RegExp("^("+P+"|[*])"),ATTR:new RegExp("^"+z),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/HTML$/i,W=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){d()},ue=we(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{R.apply(I=$.call(N.childNodes),N.childNodes),I[N.childNodes.length].nodeType}catch(e){R={apply:I.length?function(e,t){B.apply(e,$.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function le(e,t,r,i){var o,l,c,s,f,h,y,w=t&&t.ownerDocument,x=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==x&&9!==x&&11!==x)return r;if(!i&&((t?t.ownerDocument||t:N)!==p&&d(t),t=t||p,g)){if(11!==x&&(f=_.exec(e)))if(o=f[1]){if(9===x){if(!(c=t.getElementById(o)))return r;if(c.id===o)return r.push(c),r}else if(w&&(c=w.getElementById(o))&&v(t,c)&&c.id===o)return r.push(c),r}else{if(f[2])return R.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return R.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!A[e+" "]&&(!m||!m.test(e))&&(1!==x||"object"!==t.nodeName.toLowerCase())){if(y=e,w=t,1===x&&V.test(e)){(s=t.getAttribute("id"))?s=s.replace(re,ie):t.setAttribute("id",s=b),l=(h=u(e)).length;while(l--)h[l]="#"+s+" "+ye(h[l]);y=h.join(","),w=ee.test(e)&&ge(t.parentNode)||t}try{return R.apply(r,w.querySelectorAll(y)),r}catch(t){A(e,!0)}finally{s===b&&t.removeAttribute("id")}}}return a(e.replace(j,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ce(e){return e[b]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ue(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ce(function(t){return t=+t,ce(function(n,r){var i,o=e([],n.length,t),u=o.length;while(u--)n[i=o[u]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}n=le.support={},o=le.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Q.test(t||n&&n.nodeName||"HTML")},d=le.setDocument=function(e){var t,i,u=e?e.ownerDocument||e:N;return u!==p&&9===u.nodeType&&u.documentElement?(p=u,h=p.documentElement,g=!o(p),N!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",oe,!1):i.attachEvent&&i.attachEvent("onunload",oe)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=b,!p.getElementsByName||!p.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if(void 0!==t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+M+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+b+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||m.push(".#.+[+~]")}),se(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(n.matchesSelector=Z.test(w=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=w.call(e,"*"),w.call(e,"[s!='']:x"),y.push("!=",F)}),m=m.length&&new RegExp(m.join("|")),y=y.length&&new RegExp(y.join("|")),t=Z.test(h.compareDocumentPosition),v=t||Z.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===N&&v(N,e)?-1:t===p||t.ownerDocument===N&&v(N,t)?1:s?k(s,e)-k(s,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:s?k(s,e)-k(s,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?de(u[r],l[r]):u[r]===N?-1:l[r]===N?1:0},p):p},le.matches=function(e,t){return le(e,null,null,t)},le.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),n.matchesSelector&&g&&!A[t+" "]&&(!y||!y.test(t))&&(!m||!m.test(t)))try{var r=w.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){A(t,!0)}return le(t,p,null,[e]).length>0},le.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),v(e,t)},le.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},le.escape=function(e){return(e+"").replace(re,ie)},le.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},le.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,s=!n.sortStable&&e.slice(0),e.sort(T),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return s=null,e},i=le.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=le.selectors={cacheLength:50,createPseudo:ce,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||le.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&le.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=u(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=le.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(O," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),u="last"!==e.slice(-4),l="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,a){var c,s,f,d,p,h,g=o!==u?"nextSibling":"previousSibling",m=t.parentNode,y=l&&t.nodeName.toLowerCase(),w=!a&&!l,v=!1;if(m){if(o){while(g){d=t;while(d=d[g])if(l?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[u?m.firstChild:m.lastChild],u&&w){v=(p=(c=(s=(f=(d=m)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1])&&c[2],d=p&&m.childNodes[p];while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if(1===d.nodeType&&++v&&d===t){s[e]=[x,p,v];break}}else if(w&&(v=p=(c=(s=(f=(d=t)[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===x&&c[1]),!1===v)while(d=++p&&d&&d[g]||(v=p=0)||h.pop())if((l?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++v&&(w&&((s=(f=d[b]||(d[b]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[x,v]),d===t))break;return(v-=i)===r||v%r==0&&v/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||le.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ce(function(e,n){var r,o=i(e,t),u=o.length;while(u--)e[r=k(e,o[u])]=!(n[r]=o[u])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ce(function(e){var t=[],n=[],r=l(e.replace(j,"$1"));return r[b]?ce(function(e,t,n,i){var o,u=r(e,null,i,[]),l=e.length;while(l--)(o=u[l])&&(e[l]=!(t[l]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ce(function(e){return function(t){return le(e,t).length>0}}),contains:ce(function(e){return e=e.replace(te,ne),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:ce(function(e){return J.test(e||"")||le.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return W.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n>t?t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=function(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=function(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}(t);function me(){}me.prototype=r.filters=r.pseudos,r.setFilters=new me,u=le.tokenize=function(e,t){var n,i,o,u,l,a,c,s=D[e+" "];if(s)return t?0:s.slice(0);l=e,a=[],c=r.preFilter;while(l){n&&!(i=G.exec(l))||(i&&(l=l.slice(i[0].length)||l),a.push(o=[])),n=!1,(i=U.exec(l))&&(n=i.shift(),o.push({value:n,type:i[0].replace(j," ")}),l=l.slice(n.length));for(u in r.filter)!(i=K[u].exec(l))||c[u]&&!(i=c[u](i))||(n=i.shift(),o.push({value:n,type:u,matches:i}),l=l.slice(n.length));if(!n)break}return t?l.length:l?le.error(e):D(e,a).slice(0)};function ye(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function we(e,t,n){var r=t.dir,i=t.next,o=i||r,u=n&&"parentNode"===o,l=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||u)return e(t,n,i);return!1}:function(t,n,a){var c,s,f,d=[x,l];if(a){while(t=t[r])if((1===t.nodeType||u)&&e(t,n,a))return!0}else while(t=t[r])if(1===t.nodeType||u)if(f=t[b]||(t[b]={}),s=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((c=s[o])&&c[0]===x&&c[1]===l)return d[2]=c[2];if(s[o]=d,d[2]=e(t,n,a))return!0}return!1}}function ve(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)le(e,t[r],n);return n}function Ne(e,t,n,r,i){for(var o,u=[],l=0,a=e.length,c=null!=t;l<a;l++)(o=e[l])&&(n&&!n(o,r,i)||(u.push(o),c&&t.push(l)));return u}function xe(e,t,n,r,i,o){return r&&!r[b]&&(r=xe(r)),i&&!i[b]&&(i=xe(i,o)),ce(function(o,u,l,a){var c,s,f,d=[],p=[],h=u.length,g=o||be(t||"*",l.nodeType?[l]:l,[]),m=!e||!o&&t?g:Ne(g,d,e,l,a),y=n?i||(o?e:h||r)?[]:u:m;if(n&&n(m,y,l,a),r){c=Ne(y,p),r(c,[],l,a),s=c.length;while(s--)(f=c[s])&&(y[p[s]]=!(m[p[s]]=f))}if(o){if(i||e){if(i){c=[],s=y.length;while(s--)(f=y[s])&&c.push(m[s]=f);i(null,y=[],c,a)}s=y.length;while(s--)(f=y[s])&&(c=i?k(o,f):d[s])>-1&&(o[c]=!(u[c]=f))}}else y=Ne(y===u?y.splice(h,y.length):y),i?i(null,u,y,a):R.apply(u,y)})}function Ce(e){for(var t,n,i,o=e.length,u=r.relative[e[0].type],l=u||r.relative[" "],a=u?1:0,s=we(function(e){return e===t},l,!0),f=we(function(e){return k(t,e)>-1},l,!0),d=[function(e,n,r){var i=!u&&(r||n!==c)||((t=n).nodeType?s(e,n,r):f(e,n,r));return t=null,i}];a<o;a++)if(n=r.relative[e[a].type])d=[we(ve(d),n)];else{if((n=r.filter[e[a].type].apply(null,e[a].matches))[b]){for(i=++a;i<o;i++)if(r.relative[e[i].type])break;return xe(a>1&&ve(d),a>1&&ye(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(j,"$1"),n,a<i&&Ce(e.slice(a,i)),i<o&&Ce(e=e.slice(i)),i<o&&ye(e))}d.push(n)}return ve(d)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,u,l,a,s){var f,h,m,y=0,w="0",v=o&&[],b=[],N=c,C=o||i&&r.find.TAG("*",s),E=x+=null==N?1:Math.random()||.1,D=C.length;for(s&&(c=u===p||u||s);w!==D&&null!=(f=C[w]);w++){if(i&&f){h=0,u||f.ownerDocument===p||(d(f),l=!g);while(m=e[h++])if(m(f,u||p,l)){a.push(f);break}s&&(x=E)}n&&((f=!m&&f)&&y--,o&&v.push(f))}if(y+=w,n&&w!==y){h=0;while(m=t[h++])m(v,b,u,l);if(o){if(y>0)while(w--)v[w]||b[w]||(b[w]=q.call(a));b=Ne(b)}R.apply(a,b),s&&!o&&b.length>0&&y+t.length>1&&le.uniqueSort(a)}return s&&(x=E,c=N),v};return n?ce(o):o}l=le.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=u(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},a=le.select=function(e,t,n,i){var o,a,c,s,f,d="function"==typeof e&&e,p=!i&&u(e=d.selector||e);if(n=n||[],1===p.length){if((a=p[0]=p[0].slice(0)).length>2&&"ID"===(c=a[0]).type&&9===t.nodeType&&g&&r.relative[a[1].type]){if(!(t=(r.find.ID(c.matches[0].replace(te,ne),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(a.shift().value.length)}o=K.needsContext.test(e)?0:a.length;while(o--){if(c=a[o],r.relative[s=c.type])break;if((f=r.find[s])&&(i=f(c.matches[0].replace(te,ne),ee.test(a[0].type)&&ge(t.parentNode)||t))){if(a.splice(o,1),!(e=i.length&&ye(a)))return R.apply(n,i),n;break}}}return(d||l(e,p))(i,t,!g,n,!t||ee.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(T).join("")===b,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||fe(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});var De=e.Sizzle;le.noConflict=function(){return e.Sizzle===le&&(e.Sizzle=De),le},"function"==typeof define&&define.amd?define(function(){return le}):"undefined"!=typeof module&&module.exports?module.exports=le:e.Sizzle=le}(window); //# sourceMappingURL=sizzle.min.map \ No newline at end of file diff --git a/dist/sizzle.min.map b/dist/sizzle.min.map index aff2249..10d432c 100644 --- a/dist/sizzle.min.map +++ b/dist/sizzle.min.map @@ -1 +1 @@ -{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","push_native","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","last","simple","forward","ofType","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","innerText","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAWA,GAEX,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EAAU,SAAW,EAAI,IAAIC,KAC7BC,EAAetB,EAA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C1C,IAAIoM,EACJ,IAAMpM,EACL,OAAwB,IAAjBqC,EAAM8J,GAAkBA,EAAK7G,eACjC8G,EAAM/J,EAAKqI,iBAAkByB,KAAWC,EAAIE,UAC7CF,EAAInE,MACL,OAMJ,IAAIoN,GAAU1V,EAAOsG,OAErBA,GAAOqP,WAAa,WAKnB,OAJK3V,EAAOsG,SAAWA,KACtBtG,EAAOsG,OAASoP,IAGVpP,IAGe,mBAAXsP,QAAyBA,OAAOC,IAC3CD,OAAO,WAAa,OAAOtP,KAEE,oBAAXwP,QAA0BA,OAAOC,QACnDD,OAAOC,QAAUzP,GAEjBtG,EAAOsG,OAASA,GAvtEjB,CA2tEItG","file":"sizzle.min.js"} \ No newline at end of file +{"version":3,"sources":["sizzle.js"],"names":["window","i","support","Expr","getText","isXML","tokenize","compile","select","outermostContext","sortInput","hasDuplicate","setDocument","document","docElem","documentIsHTML","rbuggyQSA","rbuggyMatches","matches","contains","expando","Date","preferredDoc","dirruns","done","classCache","createCache","tokenCache","compilerCache","nonnativeSelectorCache","sortOrder","a","b","hasOwn","hasOwnProperty","arr","pop","push_native","push","slice","indexOf","list","elem","len","length","booleans","whitespace","identifier","attributes","pseudos","rwhitespace","RegExp","rtrim","rcomma","rcombinators","rdescend","rpseudo","ridentifier","matchExpr","ID","CLASS","TAG","ATTR","PSEUDO","CHILD","bool","needsContext","rhtml","rinputs","rheader","rnative","rquickExpr","rsibling","runescape","funescape","_","escaped","escapedWhitespace","high","String","fromCharCode","rcssescape","fcssescape","ch","asCodePoint","charCodeAt","toString","unloadHandler","inDisabledFieldset","addCombinator","disabled","nodeName","toLowerCase","dir","next","apply","call","childNodes","nodeType","e","target","els","j","Sizzle","selector","context","results","seed","m","nid","match","groups","newSelector","newContext","ownerDocument","exec","getElementById","id","getElementsByTagName","getElementsByClassName","qsa","test","getAttribute","replace","setAttribute","toSelector","join","testContext","parentNode","querySelectorAll","qsaError","removeAttribute","keys","cache","key","value","cacheLength","shift","markFunction","fn","assert","el","createElement","removeChild","addHandle","attrs","handler","split","attrHandle","siblingCheck","cur","diff","sourceIndex","nextSibling","createDisabledPseudo","isDisabled","createPositionalPseudo","argument","matchIndexes","namespace","namespaceURI","documentElement","node","hasCompare","subWindow","doc","defaultView","top","addEventListener","attachEvent","className","appendChild","createComment","getById","getElementsByName","filter","attrId","find","getAttributeNode","elems","tag","tmp","innerHTML","input","matchesSelector","webkitMatchesSelector","mozMatchesSelector","oMatchesSelector","msMatchesSelector","disconnectedMatch","compareDocumentPosition","adown","bup","compare","sortDetached","aup","ap","bp","unshift","expr","elements","ret","attr","name","val","undefined","specified","escape","sel","error","msg","Error","uniqueSort","duplicates","detectDuplicates","sortStable","sort","splice","textContent","firstChild","nodeValue","selectors","createPseudo","relative",">","first"," ","+","~","preFilter","excess","unquoted","nodeNameSelector","pattern","operator","check","result","type","what","last","simple","forward","ofType","xml","uniqueCache","outerCache","nodeIndex","start","parent","useCache","lastChild","uniqueID","pseudo","args","setFilters","idx","matched","not","matcher","unmatched","has","text","innerText","lang","elemLang","hash","location","root","focus","activeElement","hasFocus","href","tabIndex","enabled","checked","selected","selectedIndex","empty","header","button","eq","even","odd","lt","gt","radio","checkbox","file","password","image","createInputPseudo","submit","reset","createButtonPseudo","prototype","filters","parseOnly","tokens","soFar","preFilters","cached","combinator","base","skip","checkNonElements","doneName","oldCache","newCache","elementMatcher","matchers","multipleContexts","contexts","condense","map","newUnmatched","mapped","setMatcher","postFilter","postFinder","postSelector","temp","preMap","postMap","preexisting","matcherIn","matcherOut","matcherFromTokens","checkContext","leadingRelative","implicitRelative","matchContext","matchAnyContext","concat","matcherFromGroupMatchers","elementMatchers","setMatchers","bySet","byElement","superMatcher","outermost","matchedCount","setMatched","contextBackup","dirrunsUnique","Math","random","token","compiled","defaultValue","_sizzle","noConflict","define","amd","module","exports"],"mappings":";CAUA,SAAWA,GAEX,IAAIC,EACHC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAGAC,EACAC,E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AMtM,GACzC,IAAMA,GAAyC,UAAhCqC,EAAKiD,SAASC,cAC5B,OAAOlD,EAAKkT,eAOThN,GAAO,SAAUC,GACtB,OAAsC,MAA/BA,EAAGnB,aAAa,eAEvBsB,GAAWnG,EAAU,SAAUH,EAAMiK,EAAMtM,GAC1C,IAAIuM,EACJ,IAAMvM,EACL,OAAwB,IAAjBqC,EAAMiK,GAAkBA,EAAK/G,eACjCgH,EAAMlK,EAAKwI,iBAAkByB,KAAWC,EAAIE,UAC7CF,EAAIrE,MACL,OAMJ,IAAIsN,GAAU7V,EAAOuG,OAErBA,GAAOuP,WAAa,WAKnB,OAJK9V,EAAOuG,SAAWA,KACtBvG,EAAOuG,OAASsP,IAGVtP,IAGe,mBAAXwP,QAAyBA,OAAOC,IAC3CD,OAAO,WAAa,OAAOxP,KAEE,oBAAX0P,QAA0BA,OAAOC,QACnDD,OAAOC,QAAU3P,GAEjBvG,EAAOuG,OAASA,GA3tEjB,CA+tEIvG","file":"sizzle.min.js"} \ No newline at end of file diff --git a/src/sizzle.js b/src/sizzle.js index 78c5930..868342d 100644 --- a/src/sizzle.js +++ b/src/sizzle.js @@ -1,1077 +1,1081 @@ /*! * Sizzle CSS Selector Engine v@VERSION * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: @DATE */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, + rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; + var namespace = elem.namespaceURI, + docElem = (elem.ownerDocument || elem).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; diff --git a/test/unit/utilities.js b/test/unit/utilities.js index 036e9da..45bec64 100644 --- a/test/unit/utilities.js +++ b/test/unit/utilities.js @@ -1,296 +1,357 @@ QUnit.module( "utilities", { beforeEach: setup } ); function testAttr( doc, assert ) { assert.expect( 9 ); var el; if ( doc ) { // XML el = doc.createElement( "input" ); el.setAttribute( "type", "checkbox" ); } else { // Set checked on creation by creating with a fragment // See https://jsfiddle.net/8sVgA/1/show/light in oldIE el = jQuery( "<input type='checkbox' checked='checked' />" )[0]; } // Set it again for good measure el.setAttribute( "checked", "checked" ); el.setAttribute( "id", "id" ); el.setAttribute( "value", "on" ); assert.strictEqual( Sizzle.attr( el, "nonexistent" ), null, "nonexistent" ); assert.strictEqual( Sizzle.attr( el, "id" ), "id", "existent" ); assert.strictEqual( Sizzle.attr( el, "value" ), "on", "value" ); assert.strictEqual( Sizzle.attr( el, "checked" ), "checked", "boolean" ); assert.strictEqual( Sizzle.attr( el, "href" ), null, "interpolation risk" ); assert.strictEqual( Sizzle.attr( el, "constructor" ), null, "Object.prototype property \"constructor\" (negative)" ); assert.strictEqual( Sizzle.attr( el, "watch" ), null, "Gecko Object.prototype property \"watch\" (negative)" ); el.setAttribute( "constructor", "foo" ); el.setAttribute( "watch", "bar" ); assert.strictEqual( Sizzle.attr( el, "constructor" ), "foo", "Object.prototype property \"constructor\"" ); assert.strictEqual( Sizzle.attr( el, "watch" ), "bar", "Gecko Object.prototype property \"watch\"" ); } QUnit.test("Sizzle.attr (HTML)", function( assert ) { testAttr( null, assert ); }); QUnit.test("Sizzle.attr (XML)", function( assert ) { testAttr( jQuery.parseXML( "<root/>" ), assert ); }); QUnit.test("Sizzle.escape", function( assert ) { // Edge cases assert.equal( Sizzle.escape(), "undefined", "Converts undefined to string" ); assert.equal( Sizzle.escape("-"), "\\-", "Escapes standalone dash" ); assert.equal( Sizzle.escape("-a"), "-a", "Doesn't escape leading dash followed by non-number" ); assert.equal( Sizzle.escape("--"), "--", "Doesn't escape standalone double dash" ); assert.equal( Sizzle.escape( "\uFFFD" ), "\uFFFD", "Doesn't escape standalone replacement character" ); assert.equal( Sizzle.escape( "a\uFFFD" ), "a\uFFFD", "Doesn't escape trailing replacement character" ); assert.equal( Sizzle.escape( "\uFFFDb" ), "\uFFFDb", "Doesn't escape leading replacement character" ); assert.equal( Sizzle.escape( "a\uFFFDb" ), "a\uFFFDb", "Doesn't escape embedded replacement character" ); // Derived from CSSOM tests // https://test.csswg.org/harness/test/cssom-1_dev/section/7.1/ // String conversion assert.equal( Sizzle.escape( true ), "true", "Converts boolean true to string" ); assert.equal( Sizzle.escape( false ), "false", "Converts boolean true to string" ); assert.equal( Sizzle.escape( null ), "null", "Converts null to string" ); assert.equal( Sizzle.escape( "" ), "", "Doesn't modify empty string" ); // Null bytes assert.equal( Sizzle.escape( "\0" ), "\uFFFD", "Escapes null-character input as replacement character" ); assert.equal( Sizzle.escape( "a\0" ), "a\uFFFD", "Escapes trailing-null input as replacement character" ); assert.equal( Sizzle.escape( "\0b" ), "\uFFFDb", "Escapes leading-null input as replacement character" ); assert.equal( Sizzle.escape( "a\0b" ), "a\uFFFDb", "Escapes embedded-null input as replacement character" ); // Number prefix assert.equal( Sizzle.escape( "0a" ), "\\30 a", "Escapes leading 0" ); assert.equal( Sizzle.escape( "1a" ), "\\31 a", "Escapes leading 1" ); assert.equal( Sizzle.escape( "2a" ), "\\32 a", "Escapes leading 2" ); assert.equal( Sizzle.escape( "3a" ), "\\33 a", "Escapes leading 3" ); assert.equal( Sizzle.escape( "4a" ), "\\34 a", "Escapes leading 4" ); assert.equal( Sizzle.escape( "5a" ), "\\35 a", "Escapes leading 5" ); assert.equal( Sizzle.escape( "6a" ), "\\36 a", "Escapes leading 6" ); assert.equal( Sizzle.escape( "7a" ), "\\37 a", "Escapes leading 7" ); assert.equal( Sizzle.escape( "8a" ), "\\38 a", "Escapes leading 8" ); assert.equal( Sizzle.escape( "9a" ), "\\39 a", "Escapes leading 9" ); // Letter-number prefix assert.equal( Sizzle.escape( "a0b" ), "a0b", "Doesn't escape embedded 0" ); assert.equal( Sizzle.escape( "a1b" ), "a1b", "Doesn't escape embedded 1" ); assert.equal( Sizzle.escape( "a2b" ), "a2b", "Doesn't escape embedded 2" ); assert.equal( Sizzle.escape( "a3b" ), "a3b", "Doesn't escape embedded 3" ); assert.equal( Sizzle.escape( "a4b" ), "a4b", "Doesn't escape embedded 4" ); assert.equal( Sizzle.escape( "a5b" ), "a5b", "Doesn't escape embedded 5" ); assert.equal( Sizzle.escape( "a6b" ), "a6b", "Doesn't escape embedded 6" ); assert.equal( Sizzle.escape( "a7b" ), "a7b", "Doesn't escape embedded 7" ); assert.equal( Sizzle.escape( "a8b" ), "a8b", "Doesn't escape embedded 8" ); assert.equal( Sizzle.escape( "a9b" ), "a9b", "Doesn't escape embedded 9" ); // Dash-number prefix assert.equal( Sizzle.escape( "-0a" ), "-\\30 a", "Escapes 0 after leading dash" ); assert.equal( Sizzle.escape( "-1a" ), "-\\31 a", "Escapes 1 after leading dash" ); assert.equal( Sizzle.escape( "-2a" ), "-\\32 a", "Escapes 2 after leading dash" ); assert.equal( Sizzle.escape( "-3a" ), "-\\33 a", "Escapes 3 after leading dash" ); assert.equal( Sizzle.escape( "-4a" ), "-\\34 a", "Escapes 4 after leading dash" ); assert.equal( Sizzle.escape( "-5a" ), "-\\35 a", "Escapes 5 after leading dash" ); assert.equal( Sizzle.escape( "-6a" ), "-\\36 a", "Escapes 6 after leading dash" ); assert.equal( Sizzle.escape( "-7a" ), "-\\37 a", "Escapes 7 after leading dash" ); assert.equal( Sizzle.escape( "-8a" ), "-\\38 a", "Escapes 8 after leading dash" ); assert.equal( Sizzle.escape( "-9a" ), "-\\39 a", "Escapes 9 after leading dash" ); // Double dash prefix assert.equal( Sizzle.escape( "--a" ), "--a", "Doesn't escape leading double dash" ); // Miscellany assert.equal( Sizzle.escape( "\x01\x02\x1E\x1F" ), "\\1 \\2 \\1e \\1f ", "Escapes C0 control characters" ); assert.equal( Sizzle.escape( "\x80\x2D\x5F\xA9" ), "\x80\x2D\x5F\xA9", "Doesn't escape general punctuation or non-ASCII ISO-8859-1 characters" ); assert.equal( Sizzle.escape( "\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90" + "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F" ), "\\7f \x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90" + "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F", "Escapes DEL control character" ); assert.equal( Sizzle.escape( "\xA0\xA1\xA2" ), "\xA0\xA1\xA2", "Doesn't escape non-ASCII ISO-8859-1 characters" ); assert.equal( Sizzle.escape( "a0123456789b" ), "a0123456789b", "Doesn't escape embedded numbers" ); assert.equal( Sizzle.escape( "abcdefghijklmnopqrstuvwxyz" ), "abcdefghijklmnopqrstuvwxyz", "Doesn't escape lowercase ASCII letters" ); assert.equal( Sizzle.escape( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "Doesn't escape uppercase ASCII letters" ); assert.equal( Sizzle.escape( "\x20\x21\x78\x79" ), "\\ \\!xy", "Escapes non-word ASCII characters" ); // Astral symbol (U+1D306 TETRAGRAM FOR CENTRE) assert.equal( Sizzle.escape( "\uD834\uDF06" ), "\uD834\uDF06", "Doesn't escape astral characters" ); // Lone surrogates assert.equal( Sizzle.escape( "\uDF06" ), "\uDF06", "Doesn't escape lone low surrogate" ); assert.equal( Sizzle.escape( "\uD834" ), "\uD834", "Doesn't escape lone high surrogate" ); }); QUnit.test("Sizzle.contains", function( assert ) { assert.expect( 16 ); var container = document.getElementById("nonnodes"), element = container.firstChild, text = element.nextSibling, nonContained = container.nextSibling, detached = document.createElement("a"); assert.ok( element && element.nodeType === 1, "preliminary: found element" ); assert.ok( text && text.nodeType === 3, "preliminary: found text" ); assert.ok( nonContained, "preliminary: found non-descendant" ); assert.ok( Sizzle.contains(container, element), "child" ); assert.ok( Sizzle.contains(container.parentNode, element), "grandchild" ); assert.ok( Sizzle.contains(container, text), "text child" ); assert.ok( Sizzle.contains(container.parentNode, text), "text grandchild" ); assert.ok( !Sizzle.contains(container, container), "self" ); assert.ok( !Sizzle.contains(element, container), "parent" ); assert.ok( !Sizzle.contains(container, nonContained), "non-descendant" ); assert.ok( !Sizzle.contains(container, document), "document" ); assert.ok( !Sizzle.contains(container, document.documentElement), "documentElement (negative)" ); assert.ok( !Sizzle.contains(container, null), "Passing null does not throw an error" ); assert.ok( Sizzle.contains(document, document.documentElement), "documentElement (positive)" ); assert.ok( Sizzle.contains(document, element), "document container (positive)" ); assert.ok( !Sizzle.contains(document, detached), "document container (negative)" ); }); if ( jQuery( "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='1' width='1'><g/></svg>" )[ 0 ].firstChild ) { QUnit.test("Sizzle.contains in SVG (jQuery #10832)", function( assert ) { assert.expect( 4 ); var svg = jQuery( "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='1' width='1'>" + "<g><circle cx='1' cy='1' r='1' /></g>" + "</svg>" ).appendTo("#qunit-fixture")[0]; assert.ok( Sizzle.contains( svg, svg.firstChild ), "root child" ); assert.ok( Sizzle.contains( svg.firstChild, svg.firstChild.firstChild ), "element child" ); assert.ok( Sizzle.contains( svg, svg.firstChild.firstChild ), "root granchild" ); assert.ok( !Sizzle.contains( svg.firstChild.firstChild, svg.firstChild ), "parent (negative)" ); }); } +QUnit.test("Sizzle.isXML", function( assert ) { + assert.expect( 10 ); + + var svgTree, + xmlTree = jQuery.parseXML( "<docElem><elem/></docElem>" ).documentElement, + htmlTree = jQuery( "<div>" + + "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='1' width='1'>" + + "<desc></desc>" + + "</svg>" + + "</div>" + )[ 0 ], + supportsSVG = /svg/i.test( htmlTree.firstChild.namespaceURI ); + + // Support: IE<=8 + // Omit the SVG DOCTYPE if it is not understood + try { + svgTree = jQuery.parseXML( + "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" " + + "\"http://www.w3.org/Gaphics/SVG/1.1/DTD/svg11.dtd\">" + + "<svg version='1.1' xmlns='http://www.w3.org/2000/svg'><desc/></svg>" + ).documentElement; + } catch ( ex ) { + svgTree = jQuery.parseXML( + "<svg version='1.1' xmlns='http://www.w3.org/2000/svg'><desc/></svg>" + ).documentElement; + } + + assert.strictEqual( Sizzle.isXML( xmlTree ), true, "XML element" ); + assert.strictEqual( Sizzle.isXML( xmlTree.firstChild ), true, "XML child element" ); + + assert.strictEqual( Sizzle.isXML( svgTree ), true, "SVG root element" ); + assert.strictEqual( Sizzle.isXML( svgTree.firstChild ), true, "SVG child element" ); + + assert.strictEqual( Sizzle.isXML( htmlTree ), false, "disconnected div element" ); + assert.strictEqual( Sizzle.isXML( htmlTree.firstChild ), supportsSVG, + "disconnected HTML-embedded SVG root element" ); + + // Support: IE 7 only + // The DOM under foreign elements can be incomplete + if ( htmlTree.firstChild.firstChild ) { + assert.strictEqual( Sizzle.isXML( htmlTree.firstChild.firstChild ), supportsSVG, + "disconnected HTML-embedded SVG child element" ); + } else { + assert.ok( true, "Cannot test an incomplete DOM" ); + } + + document.getElementById( "qunit-fixture" ).appendChild( htmlTree ); + assert.strictEqual( Sizzle.isXML( htmlTree ), false, "connected div element" ); + assert.strictEqual( Sizzle.isXML( htmlTree.firstChild ), supportsSVG, + "connected HTML-embedded SVG root element" ); + + // Support: IE 7 only + // The DOM under foreign elements can be incomplete + if ( htmlTree.firstChild.firstChild ) { + assert.strictEqual( Sizzle.isXML( htmlTree.firstChild.firstChild ), supportsSVG, + "disconnected HTML-embedded SVG child element" ); + } else { + assert.ok( true, "Cannot test an incomplete DOM" ); + } +}); + QUnit.test("Sizzle.uniqueSort", function( assert ) { assert.expect( 14 ); function Arrayish( arr ) { var i = this.length = arr.length; while ( i-- ) { this[ i ] = arr[ i ]; } } Arrayish.prototype = { slice: [].slice, sort: [].sort, splice: [].splice }; var i, tests, detached = [], body = document.body, fixture = document.getElementById("qunit-fixture"), detached1 = document.createElement("p"), detached2 = document.createElement("ul"), detachedChild = detached1.appendChild( document.createElement("a") ), detachedGrandchild = detachedChild.appendChild( document.createElement("b") ); for ( i = 0; i < 12; i++ ) { detached.push( document.createElement("li") ); detached[i].id = "detached" + i; detached2.appendChild( document.createElement("li") ).id = "detachedChild" + i; } tests = { "Empty": { input: [], expected: [] }, "Single-element": { input: [ fixture ], expected: [ fixture ] }, "No duplicates": { input: [ fixture, body ], expected: [ body, fixture ] }, "Duplicates": { input: [ body, fixture, fixture, body ], expected: [ body, fixture ] }, "Detached": { input: detached.slice( 0 ), expected: detached.slice( 0 ) }, "Detached children": { input: [ detached2.childNodes[3], detached2.childNodes[0], detached2.childNodes[2], detached2.childNodes[1] ], expected: [ detached2.childNodes[0], detached2.childNodes[1], detached2.childNodes[2], detached2.childNodes[3] ] }, "Attached/detached mixture": { input: [ detached1, fixture, detached2, document, detachedChild, body, detachedGrandchild ], expected: [ document, body, fixture ], length: 3 } }; jQuery.each( tests, function( label, test ) { var length = test.length || test.input.length; assert.deepEqual( Sizzle.uniqueSort( test.input ).slice( 0, length ), test.expected, label + " (array)" ); assert.deepEqual( Sizzle.uniqueSort( new Arrayish( test.input ) ).slice( 0, length ), test.expected, label + " (quasi-array)" ); }); }); testIframeWithCallback( "Sizzle.uniqueSort works cross-window (jQuery #14381)", "mixed_sort.html", function( actual, expected, message ) { var assert = this; assert.deepEqual( actual, expected, message ); } ); testIframeWithCallback( "Sizzle.noConflict", "noConflict.html", function( reporter ) { var assert = this; reporter( assert ); } );
jquery/sizzle
54bc2dd385a54851c897bc371fed05921b5ab65f
Build: Update tested browsers, fix iOS configuration
diff --git a/Gruntfile.js b/Gruntfile.js index 0db803e..645508d 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,288 +1,288 @@ module.exports = function( grunt ) { "use strict"; var gzip = require( "gzip-js" ), isBrowserStack = process.env.BROWSER_STACK_USERNAME && process.env.BROWSER_STACK_ACCESS_KEY, browsers = { phantom: [ "PhantomJS" ], desktop: [], android: [], ios: [], old: { firefox: [], chrome: [], safari: [], ie: [], opera: [], android: [] } }, files = { source: "src/sizzle.js", speed: "speed/speed.js", tests: "test/unit/*.js", karma: "test/karma/*.js", grunt: [ "Gruntfile.js", "tasks/*" ] }; // if Browserstack is set up, assume we can use it if ( isBrowserStack ) { // See https://github.com/jquery/sizzle/wiki/Sizzle-Documentation#browsers browsers.desktop = [ "bs_chrome-45", // shares V8 with Node.js 4 LTS - "bs_chrome-69", "bs_chrome-70", + "bs_chrome-70", "bs_chrome-71", "bs_firefox-52", "bs_firefox-60", // Firefox ESR - "bs_firefox-61", "bs_firefox-62", + "bs_firefox-63", "bs_firefox-64", - "bs_edge-16", "bs_edge-17", + "bs_edge-17", "bs_edge-18", "bs_ie-9", "bs_ie-10", "bs_ie-11", - "bs_opera-55", "bs_opera-56", + "bs_opera-56", "bs_opera-57", // Real Safari 6.1 and 7.0 are not available "bs_safari-6.0", "bs_safari-8.0", "bs_safari-9.1", "bs_safari-10.1", "bs_safari-11.1", "bs_safari-12.0", ]; browsers.ios = [ "bs_ios-5.1", "bs_ios-6.0", "bs_ios-7.0", "bs_ios-8.3", "bs_ios-9.3", "bs_ios-10.3", - "bs_ios-11.4", "bs_ios-12.0", + "bs_ios-11.4", "bs_ios-12.1", ]; browsers.android = [ "bs_android-4.0", "bs_android-4.1", "bs_android-4.2", "bs_android-4.3", "bs_android-4.4" ]; browsers.old = { firefox: [ "bs_firefox-3.6" ], chrome: [ "bs_chrome-16" ], safari: [ "bs_safari-4.0", "bs_safari-5.0", "bs_safari-5.1" ], ie: [ "bs_ie-7", "bs_ie-8" ], opera: [ "bs_opera-11.6", "bs_opera-12.16" ], android: [ "bs_android-2.3" ] }; } // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON( "package.json" ), dateString: new Date().toISOString().replace( /\..*Z/, "" ), compile: { all: { dest: "dist/sizzle.js", src: "src/sizzle.js" } }, version: { files: [ "package.json", "bower.json" ] }, uglify: { all: { files: { "dist/sizzle.min.js": [ "dist/sizzle.js" ] }, options: { compress: { "hoist_funs": false, loops: false }, output: { ascii_only: true }, banner: "/*! Sizzle v<%= pkg.version %> | (c) " + "JS Foundation and other contributors | js.foundation */", sourceMap: true, sourceMapName: "dist/sizzle.min.map" } } }, "ensure_ascii": { files: [ "dist/*.js" ] }, "compare_size": { files: [ "dist/sizzle.js", "dist/sizzle.min.js" ], options: { compress: { gz: function( contents ) { return gzip.zip( contents, {} ).length; } }, cache: "dist/.sizecache.json" } }, npmcopy: { all: { options: { destPrefix: "external" }, files: { "benchmark/benchmark.js": "benchmark/benchmark.js", "benchmark/LICENSE.txt": "benchmark/LICENSE.txt", "jquery/jquery.js": "jquery/jquery.js", "jquery/MIT-LICENSE.txt": "jquery/MIT-LICENSE.txt", "qunit/qunit.js": "qunitjs/qunit/qunit.js", "qunit/qunit.css": "qunitjs/qunit/qunit.css", "qunit/LICENSE.txt": "qunitjs/LICENSE.txt", "requirejs/require.js": "requirejs/require.js", "requirejs-domready/domReady.js": "requirejs-domready/domReady.js", "requirejs-text/text.js": "requirejs-text/text.js", } } }, jshint: { options: { jshintrc: true }, all: { src: [ files.source, files.grunt, files.karma, files.speed, files.tests ] } }, jscs: { src: { options: { requireDotNotation: null }, src: [ files.source ] }, grunt: { options: { requireCamelCaseOrUpperCaseIdentifiers: null }, src: [ files.grunt ] }, speed: [ files.speed ], tests: { options: { maximumLineLength: null }, src: [ files.tests ] }, karma: { options: { requireCamelCaseOrUpperCaseIdentifiers: null }, src: [ files.karma ] } }, jsonlint: { pkg: { src: [ "package.json" ] }, bower: { src: [ "bower.json" ] } }, karma: { options: { configFile: "test/karma/karma.conf.js", singleRun: true }, watch: { background: true, singleRun: false, browsers: browsers.phantom }, phantom: { browsers: browsers.phantom }, desktop: { browsers: browsers.desktop }, android: { browsers: browsers.android }, ios: { browsers: browsers.ios }, oldIe: { browsers: browsers.old.ie, // Support: IE <=8 only // Force use of JSONP polling transports: [ "polling" ], forceJSONP: true }, oldOpera: { browsers: browsers.old.opera }, oldFirefox: { browsers: browsers.old.firefox }, oldChrome: { browsers: browsers.old.chrome }, oldSafari: { browsers: browsers.old.safari }, oldAndroid: { browsers: browsers.old.android }, all: { browsers: browsers.phantom.concat( browsers.desktop, browsers.ios, browsers.android, browsers.old.firefox, browsers.old.chrome, browsers.old.safari, browsers.old.ie, browsers.old.opera, browsers.old.android ) } }, watch: { options: { livereload: true }, files: [ files.source, files.grunt, files.karma, files.speed, "test/**/*", "test/*.html", "{package,bower}.json" ], tasks: [ "build", "karma:watch:run" ] } }); // Integrate Sizzle specific tasks grunt.loadTasks( "tasks" ); // Load dev dependencies require( "load-grunt-tasks" )( grunt ); grunt.registerTask( "lint", [ "jsonlint", "jshint", "jscs" ] ); grunt.registerTask( "start", [ "karma:watch:start", "watch" ] ); // Execute tests all browsers in sequential way, // so slow connections would not affect other runs grunt.registerTask( "tests", isBrowserStack ? [ "karma:phantom", "karma:desktop", "karma:ios", "karma:oldIe", "karma:oldFirefox", "karma:oldChrome", "karma:oldSafari", "karma:oldOpera" // See #314 :-( // "karma:android", "karma:oldAndroid" ] : "karma:phantom" ); grunt.registerTask( "build", [ "lint", "compile", "uglify", "dist", "ensure_ascii" ] ); grunt.registerTask( "default", [ "build", "tests", "compare_size" ] ); grunt.registerTask( "bower", "bowercopy" ); }; diff --git a/test/karma/launchers.js b/test/karma/launchers.js index 7bb36fc..f921031 100644 --- a/test/karma/launchers.js +++ b/test/karma/launchers.js @@ -1,307 +1,307 @@ "use strict"; module.exports = { "bs_firefox-3.6": { base: "BrowserStack", browser: "firefox", browser_version: "3.6", os: "OS X", os_version: "Mavericks" }, "bs_firefox-52": { base: "BrowserStack", browser: "firefox", browser_version: "52.0", os: "OS X", os_version: "Sierra" }, "bs_firefox-60": { base: "BrowserStack", browser: "firefox", browser_version: "60.0", os: "OS X", os_version: "High Sierra" }, - "bs_firefox-61": { + "bs_firefox-63": { base: "BrowserStack", browser: "firefox", - browser_version: "61.0", + browser_version: "63.0", os: "OS X", os_version: "Mojave" }, - "bs_firefox-62": { + "bs_firefox-64": { base: "BrowserStack", browser: "firefox", - browser_version: "62.0", + browser_version: "64.0", os: "OS X", os_version: "Mojave" }, "bs_chrome-16": { base: "BrowserStack", browser: "chrome", browser_version: "16.0", os: "OS X", os_version: "Mavericks" }, "bs_chrome-45": { base: "BrowserStack", browser: "chrome", browser_version: "45.0", os: "OS X", os_version: "Sierra" }, - "bs_chrome-69": { + "bs_chrome-70": { base: "BrowserStack", browser: "chrome", - browser_version: "69.0", + browser_version: "70.0", os: "OS X", os_version: "Mojave" }, - "bs_chrome-70": { + "bs_chrome-71": { base: "BrowserStack", browser: "chrome", - browser_version: "70.0", + browser_version: "71.0", os: "OS X", os_version: "Mojave" }, - "bs_edge-16": { + "bs_edge-17": { base: "BrowserStack", browser: "edge", - browser_version: "16.0", + browser_version: "17.0", os: "Windows", os_version: "10" }, - "bs_edge-17": { + "bs_edge-18": { base: "BrowserStack", browser: "edge", - browser_version: "17.0", + browser_version: "18.0", os: "Windows", os_version: "10" }, "bs_ie-6": { base: "BrowserStack", browser: "ie", browser_version: "6.0", os: "Windows", os_version: "XP" }, "bs_ie-7": { base: "BrowserStack", browser: "ie", browser_version: "7.0", os: "Windows", os_version: "XP" }, "bs_ie-8": { base: "BrowserStack", browser: "ie", browser_version: "8.0", os: "Windows", os_version: "7" }, "bs_ie-9": { base: "BrowserStack", browser: "ie", browser_version: "9.0", os: "Windows", os_version: "7" }, "bs_ie-10": { base: "BrowserStack", browser: "ie", browser_version: "10.0", os: "Windows", os_version: "8" }, "bs_ie-11": { base: "BrowserStack", browser: "ie", browser_version: "11.0", os: "Windows", os_version: "8.1" }, "bs_opera-11.6": { base: "BrowserStack", browser: "opera", browser_version: "11.6", os: "Windows", os_version: "7" }, "bs_opera-12.16": { base: "BrowserStack", browser: "opera", browser_version: "12.16", os: "Windows", os_version: "7" }, - "bs_opera-55": { + "bs_opera-56": { base: "BrowserStack", browser: "opera", - browser_version: "55.0", + browser_version: "56.0", os: "OS X", os_version: "Mojave" }, - "bs_opera-56": { + "bs_opera-57": { base: "BrowserStack", browser: "opera", - browser_version: "56.0", + browser_version: "57.0", os: "OS X", os_version: "Mojave" }, "bs_safari-4.0": { base: "BrowserStack", browser: "safari", browser_version: "4.0", os: "OS X", os_version: "Snow Leopard" }, "bs_safari-5.0": { base: "BrowserStack", browser: "safari", browser_version: "5.0", os: "OS X", os_version: "Snow Leopard" }, "bs_safari-5.1": { base: "BrowserStack", browser: "safari", browser_version: "5.1", os: "OS X", os_version: "Lion" }, "bs_safari-6.0": { base: "BrowserStack", browser: "safari", browser_version: "6.0", os: "OS X", os_version: "Lion" }, "bs_safari-8.0": { base: "BrowserStack", browser: "safari", browser_version: "8.0", os: "OS X", os_version: "Yosemite" }, "bs_safari-9.1": { base: "BrowserStack", browser: "safari", browser_version: "9.1", os: "OS X", os_version: "El Capitan" }, "bs_safari-10.1": { base: "BrowserStack", browser: "safari", browser_version: "10.1", os: "OS X", os_version: "Sierra" }, "bs_safari-11.1": { base: "BrowserStack", browser: "safari", browser_version: "11.1", os: "OS X", os_version: "High Sierra" }, "bs_safari-12.0": { base: "BrowserStack", browser: "safari", browser_version: "12.0", os: "OS X", os_version: "Mojave" }, "bs_ios-5.1": { base: "BrowserStack", device: "iPhone 4S", os: "ios", os_version: "5.1" }, "bs_ios-6.0": { base: "BrowserStack", device: "iPhone 5", os: "ios", os_version: "6.0" }, "bs_ios-7.0": { base: "BrowserStack", device: "iPhone 5S", os: "ios", os_version: "7.0" }, "bs_ios-8.3": { base: "BrowserStack", device: "iPhone 6", os: "ios", os_version: "8.3" }, "bs_ios-9.3": { base: "BrowserStack", device: "iPhone 6S", os: "ios", os_version: "9.3" }, "bs_ios-10.3": { base: "BrowserStack", device: "iPhone 7", os: "ios", os_version: "10.3" }, "bs_ios-11.4": { base: "BrowserStack", device: "iPhone 6S", os: "ios", os_version: "11.4", real_mobile: true }, - "bs_ios-12.0": { + "bs_ios-12.1": { base: "BrowserStack", device: "iPhone XS", os: "ios", - os_version: "12.0", + os_version: "12.1", real_mobile: true }, "bs_android-2.3": { base: "BrowserStack", device: "Motorola Droid Razr", os: "android", os_version: "2.3" }, "bs_android-4.0": { base: "BrowserStack", device: "Motorola Razr", os: "android", os_version: "4.0" }, "bs_android-4.1": { base: "BrowserStack", device: "Google Nexus 7", os: "android", os_version: "4.1" }, "bs_android-4.2": { base: "BrowserStack", device: "LG Nexus 4", os: "android", os_version: "4.2" }, "bs_android-4.3": { base: "BrowserStack", device: "Samsung Galaxy S4", os: "android", os_version: "4.3" }, "bs_android-4.4": { base: "BrowserStack", device: "Samsung Galaxy S5", os: "android", os_version: "4.4" } };
jquery/sizzle
686f08dc3493e2e1ed3d97e4e3f80f158b1c94c8
Release: Add jquery-release script
diff --git a/build/release.js b/build/release.js new file mode 100644 index 0000000..9f12baf --- /dev/null +++ b/build/release.js @@ -0,0 +1,28 @@ +/* eslint-env node */ +module.exports = function( Release ) { + + var files = [ + "dist/sizzle.js", + "dist/sizzle.min.js", + "dist/sizzle.min.map" + ]; + + Release.define( { + npmPublish: true, + issueTracker: "github", + + generateArtifacts: function( done ) { + Release.exec( "grunt", "Grunt command failed" ); + done( files ); + }, + + // TODO Add Sizzle to the CDN, or add public opt-out interfaces to jquery-release + _copyCdnArtifacts: function() { + console.warn( "Skipping CDN artifact copy." ); + }, + _pushToCdn: function() { + console.warn( "Skipping CDN push." ); + } + } ); + +};
martindemello/clojure-swing
2e24e32767529a7eba441ba7fbd029d49eb84981
get-item method added
diff --git a/helpers/item-listener.clj b/helpers/item-listener.clj index 9d904e1..0a498dc 100644 --- a/helpers/item-listener.clj +++ b/helpers/item-listener.clj @@ -1,17 +1,21 @@ (ns swing.helpers.item-listener (:import (java.awt.event ItemListener ItemEvent))) (defn add-item-listener [component f & args] (let [listener (proxy [ItemListener] [] (itemStateChanged [event] (apply f event args))) ] (.addItemListener component listener))) (defn item-selected? [event] (= (.getStateChange event) ItemEvent/SELECTED)) (defn item-deselected? [event] (= (.getStateChange event) ItemEvent/DESELECTED)) + +(defn get-item + [event] + (.getItem event))
martindemello/clojure-swing
61e41a71869d12d761996e26cefe0c24215d0e02
add more example slides
diff --git a/examples/borderlayout.clj b/examples/borderlayout.clj index ccecb8a..3320be1 100644 --- a/examples/borderlayout.clj +++ b/examples/borderlayout.clj @@ -1,27 +1,29 @@ ; http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/border.html (ns border-layout (:import (java.awt BorderLayout Dimension ComponentOrientation)) (:import (javax.swing JButton JFrame))) (defn- add-components-to-pane [pane] (let [page-start (JButton. "page start") center (JButton. "center") line-start (JButton. "line start") page-end (JButton. "page end") line-end (JButton. "line end") ] (do (.setComponentOrientation pane ComponentOrientation/RIGHT_TO_LEFT) (doto pane (.add page-start BorderLayout/PAGE_START) (.add center BorderLayout/CENTER) (.add line-start BorderLayout/LINE_START) (.add page-end BorderLayout/PAGE_END) (.add line-end BorderLayout/LINE_END)) (.setPreferredSize center (Dimension. 200 100))))) (defn border-example [] (let [frame (JFrame. "border example") pane (.getContentPane frame) ] (add-components-to-pane pane) (.pack frame) (.setVisible frame true))) + +(border-example) diff --git a/presentation/content/presentation/_border.clj.txt b/presentation/content/presentation/_border.clj.txt index aec8022..01d4b34 100644 --- a/presentation/content/presentation/_border.clj.txt +++ b/presentation/content/presentation/_border.clj.txt @@ -1,35 +1,32 @@ --- filter: erb --- -<div style="font-size:50%"> +<div style="font-size:67%"> <% uv :lang => "scheme", :theme => 'twilight' do -%> ; http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/border.html -(ns border-layout - (:import (java.awt BorderLayout Dimension ComponentOrientation)) - (:import (javax.swing JButton JFrame))) - (defn- add-components-to-pane [pane] (let [page-start (JButton. "page start") center (JButton. "center") line-start (JButton. "line start") page-end (JButton. "page end") line-end (JButton. "line end") ] (do (.setComponentOrientation pane ComponentOrientation/RIGHT_TO_LEFT) (doto pane - (.add page-start BorderLayout/PAGE_START) + (.add page-start BorderLayout/PAGE_START) ; static class constant (.add center BorderLayout/CENTER) (.add line-start BorderLayout/LINE_START) (.add page-end BorderLayout/PAGE_END) (.add line-end BorderLayout/LINE_END)) (.setPreferredSize center (Dimension. 200 100))))) (defn border-example [] (let [frame (JFrame. "border example") pane (.getContentPane frame) ] + ; components get added to the frame's content pane (add-components-to-pane pane) (.pack frame) (.setVisible frame true))) <% end -%> </div> diff --git a/presentation/content/presentation/_listeners.clj.txt b/presentation/content/presentation/_listeners.clj.txt new file mode 100644 index 0000000..e69de29 diff --git a/presentation/content/presentation/_miglayout.clj.txt b/presentation/content/presentation/_miglayout.clj.txt new file mode 100644 index 0000000..98cdcb3 --- /dev/null +++ b/presentation/content/presentation/_miglayout.clj.txt @@ -0,0 +1,24 @@ +--- +filter: erb +--- +<div style="font-size:75%"> +<% uv :lang => "scheme", :theme => 'twilight' do -%> +(defn dynamic-non-editable-table + [] + (let [ panel (miglayout + (JPanel.) + (JTextField. 20) {:id :search-key} + (JButton. "populate table") { :id :p-button } :span + (JButton. "clear table") { :id :c-button } :wrap + (JScrollPane. (JTable. my-dynamic-table-model))) + + {:keys [p-button c-button search-key] } (components panel) ] + (add-action-listener p-button populate-table search-key) + (add-action-listener c-button clear-table) + (doto (JFrame.) + (.add panel) + (.setResizable false) + (.pack) + (.setVisible true)))) +<% end -%> +</div> diff --git a/presentation/content/presentation/index.txt b/presentation/content/presentation/index.txt index 9d570ac..d5e7e15 100644 --- a/presentation/content/presentation/index.txt +++ b/presentation/content/presentation/index.txt @@ -1,49 +1,92 @@ --- title: Webby S5 created_at: 2008-05-18 22:10:21.995012 -06:00 author: You company: Company copyright: Creative Commons filter: - erb - textile - slides layout: presentation --- h1. Clojure and Swing Using the Swing toolkit to write GUI desktop applications in Clojure h1. Why Swing? * Default java gui toolkit * No native code needed * Tons of documentation, examples and third-party widgets h1. Hello World It doesn't take much to get a Swing GUI up and running: <% uv :lang => "scheme", :theme => 'twilight' do -%> (import 'javax.swing.JOptionPane) (. JOptionPane (showMessageDialog nil "Hello World")) <% end -%> h1. Translating from Java An example from a Java Swing tutorial: <%= render :partial => 'helloworld.java', :guard => true %> h1. Translating from Java And the same example in Clojure <%= render :partial => 'helloworld.clj', :guard => true %> +h1. Listeners + +<% uv :lang => "java", :theme => "twilight" do -%> +public class Beeper ... implements ActionListener { + // argument to addActionListener is an object + // that implements ActionListener + button.addActionListener(this); + + public void actionPerformed(ActionEvent e) { + makeBeepSound(); + } +} +<% end %> + +and in clojure +<% uv :lang => "scheme", :theme => "twilight" do -%> + (.addActionListener button + (proxy [ActionListener] [] + (actionPerformed [e] (make-beep-sound)) +<% end %> + +h1. Listeners - Now with swing-utils +<% uv :lang => "scheme", :theme => "twilight" do -%> + (ns examples.event + (:use (clojure.contrib + [swing-utils :only (add-action-listener)]))) + + ;; Usage: (add-action-listener component f & args) + (add-action-listener button make-beep-sound)) +<% end %> + h1. Simple BorderLayout example <%= render :partial => 'border.clj', :guard => true %> + +h1. Simple BorderLayout example + +!screenshot-border.png! + +h1. MigLayout + +<%= render :partial => 'miglayout.clj', :guard => true %> + +h1. MigLayout + +!screenshot-mig.png! diff --git a/presentation/content/presentation/screenshot-border.png b/presentation/content/presentation/screenshot-border.png new file mode 100644 index 0000000..862fdc8 Binary files /dev/null and b/presentation/content/presentation/screenshot-border.png differ diff --git a/presentation/content/presentation/screenshot-mig.png b/presentation/content/presentation/screenshot-mig.png new file mode 100644 index 0000000..e530a92 Binary files /dev/null and b/presentation/content/presentation/screenshot-mig.png differ
martindemello/clojure-swing
c9d78728e9b92eb118658f526266b7fba05ac13e
add border layout example
diff --git a/presentation/content/presentation/_border.clj.txt b/presentation/content/presentation/_border.clj.txt new file mode 100644 index 0000000..aec8022 --- /dev/null +++ b/presentation/content/presentation/_border.clj.txt @@ -0,0 +1,35 @@ +--- +filter: erb +--- +<div style="font-size:50%"> +<% uv :lang => "scheme", :theme => 'twilight' do -%> + +; http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/border.html +(ns border-layout + (:import (java.awt BorderLayout Dimension ComponentOrientation)) + (:import (javax.swing JButton JFrame))) + +(defn- add-components-to-pane + [pane] + (let [page-start (JButton. "page start") + center (JButton. "center") + line-start (JButton. "line start") + page-end (JButton. "page end") + line-end (JButton. "line end") ] + (do + (.setComponentOrientation pane ComponentOrientation/RIGHT_TO_LEFT) + (doto pane + (.add page-start BorderLayout/PAGE_START) + (.add center BorderLayout/CENTER) + (.add line-start BorderLayout/LINE_START) + (.add page-end BorderLayout/PAGE_END) + (.add line-end BorderLayout/LINE_END)) + (.setPreferredSize center (Dimension. 200 100))))) + +(defn border-example [] + (let [frame (JFrame. "border example") pane (.getContentPane frame) ] + (add-components-to-pane pane) + (.pack frame) + (.setVisible frame true))) +<% end -%> +</div> diff --git a/presentation/content/presentation/index.txt b/presentation/content/presentation/index.txt index 6e37fcf..9d570ac 100644 --- a/presentation/content/presentation/index.txt +++ b/presentation/content/presentation/index.txt @@ -1,46 +1,49 @@ --- title: Webby S5 created_at: 2008-05-18 22:10:21.995012 -06:00 author: You company: Company copyright: Creative Commons filter: - erb - textile - slides layout: presentation --- h1. Clojure and Swing Using the Swing toolkit to write GUI desktop applications in Clojure h1. Why Swing? * Default java gui toolkit * No native code needed * Tons of documentation, examples and third-party widgets h1. Hello World It doesn't take much to get a Swing GUI up and running: <% uv :lang => "scheme", :theme => 'twilight' do -%> (import 'javax.swing.JOptionPane) (. JOptionPane (showMessageDialog nil "Hello World")) <% end -%> h1. Translating from Java An example from a Java Swing tutorial: <%= render :partial => 'helloworld.java', :guard => true %> h1. Translating from Java And the same example in Clojure <%= render :partial => 'helloworld.clj', :guard => true %> +h1. Simple BorderLayout example + +<%= render :partial => 'border.clj', :guard => true %>
martindemello/clojure-swing
bf8237171606ac9db377c65a163a3dbd8a709664
s/defn-/defn
diff --git a/helpers/mouse.clj b/helpers/mouse.clj index 2893389..ce282dc 100644 --- a/helpers/mouse.clj +++ b/helpers/mouse.clj @@ -1,26 +1,26 @@ (ns swing.helpers.mouse (:import (SwingUtilities)) (:import (java.awt.event MouseAdapter MouseListener KeyEvent))) -(defn- double-click? +(defn double-click? [event] (= 2 (.getClickCount event))) (defn left-click? [event] (SwingUtilities/isLeftMouseButton event)) (defn right-click? [event] (SwingUtilities/isRightMouseButton event)) (defn center-click? [event] (SwingUtilities/isMiddleMouseButton event)) (defn add-mouse-clicked-listener [component f & args] (let [listener (proxy [MouseAdapter] [] (mouseClicked [event] (apply f event args)))] (.addMouseListener component listener) listener))
martindemello/clojure-swing
b72d895cc403d4840b43b28494bf6276ca232a7d
item listener helper added
diff --git a/helpers/item-listener.clj b/helpers/item-listener.clj new file mode 100644 index 0000000..9d904e1 --- /dev/null +++ b/helpers/item-listener.clj @@ -0,0 +1,17 @@ +(ns swing.helpers.item-listener + (:import (java.awt.event ItemListener ItemEvent))) + +(defn add-item-listener + [component f & args] + (let [listener (proxy [ItemListener] [] + (itemStateChanged [event] + (apply f event args))) ] + (.addItemListener component listener))) + +(defn item-selected? + [event] + (= (.getStateChange event) ItemEvent/SELECTED)) + +(defn item-deselected? + [event] + (= (.getStateChange event) ItemEvent/DESELECTED))
martindemello/clojure-swing
429549e493fa0526812017fe71a660596304f5ea
jtable usage with default constructor added
diff --git a/examples/jtable.clj b/examples/jtable.clj new file mode 100644 index 0000000..95afabf --- /dev/null +++ b/examples/jtable.clj @@ -0,0 +1,17 @@ +(ns jtable-example + (:import (javax.swing JFrame JTable JScrollPane JPanel)) + (:import (java.awt Dimension))) + +(def columns ["Book" "Author"]) + +(def data [["On Lisp" "Paul Graham"] + ["Practical Common Lisp" "Peter Seibel"] + ["Programming Clojure" "Stuart Holloway"]]) + +(defn default-editable-table + [] + (let [ frame (JFrame. "Default table demo") panel (JPanel.) scroll-pane (JScrollPane. (JTable. (to-array-2d data) (into-array columns)))] + (doto frame + (.add scroll-pane) + (.pack) + (.setVisible true))))
martindemello/clojure-swing
fd7e73546e6cefbb03fce3a9cffa7cdf9ce91190
added keyboard helpers
diff --git a/helpers/keyboard.clj b/helpers/keyboard.clj new file mode 100644 index 0000000..2dbad18 --- /dev/null +++ b/helpers/keyboard.clj @@ -0,0 +1,17 @@ +(ns swing.helpers.keyboard + (:import + (java.awt.event KeyListener KeyAdapter KeyEvent InputEvent))) + +(defn char-of [e] (. KeyEvent getKeyText (. e getKeyCode))) +(defn modifier [e] (. e getModifiers)) +(defn modtext [e] (. KeyEvent getKeyModifiersText (modifier e))) +(def CTRL (. InputEvent CTRL_MASK)) +(def ALT (. InputEvent ALT_MASK)) +(defn ctrl? [e] (= CTRL (bit-and (modifier e) CTRL))) +(defn alt? [e] (= ALT (bit-and (modifier e) ALT))) + +(defn add-key-pressed-listener [component f & args] + (let [listener (proxy [KeyAdapter] [] + (keyPressed [e] (apply f e args)))] + (.addKeyListener component listener) + listener))
martindemello/clojure-swing
9ab1f1248f3498cbad2f0b37404c39e4e91537b2
helpers dir added, mouse event listener and helpers added
diff --git a/helpers/mouse.clj b/helpers/mouse.clj new file mode 100644 index 0000000..2893389 --- /dev/null +++ b/helpers/mouse.clj @@ -0,0 +1,26 @@ +(ns swing.helpers.mouse + (:import (SwingUtilities)) + (:import (java.awt.event MouseAdapter MouseListener KeyEvent))) + +(defn- double-click? + [event] + (= 2 (.getClickCount event))) + +(defn left-click? + [event] + (SwingUtilities/isLeftMouseButton event)) + +(defn right-click? + [event] + (SwingUtilities/isRightMouseButton event)) + +(defn center-click? + [event] + (SwingUtilities/isMiddleMouseButton event)) + +(defn add-mouse-clicked-listener + [component f & args] + (let [listener (proxy [MouseAdapter] [] + (mouseClicked [event] (apply f event args)))] + (.addMouseListener component listener) + listener))
martindemello/clojure-swing
90403e093d6f859bfffbb281c55d08699bc92daf
border layout example
diff --git a/examples/borderlayout.clj b/examples/borderlayout.clj new file mode 100644 index 0000000..ccecb8a --- /dev/null +++ b/examples/borderlayout.clj @@ -0,0 +1,27 @@ +; http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/border.html +(ns border-layout + (:import (java.awt BorderLayout Dimension ComponentOrientation)) + (:import (javax.swing JButton JFrame))) + +(defn- add-components-to-pane + [pane] + (let [page-start (JButton. "page start") + center (JButton. "center") + line-start (JButton. "line start") + page-end (JButton. "page end") + line-end (JButton. "line end") ] + (do + (.setComponentOrientation pane ComponentOrientation/RIGHT_TO_LEFT) + (doto pane + (.add page-start BorderLayout/PAGE_START) + (.add center BorderLayout/CENTER) + (.add line-start BorderLayout/LINE_START) + (.add page-end BorderLayout/PAGE_END) + (.add line-end BorderLayout/LINE_END)) + (.setPreferredSize center (Dimension. 200 100))))) + +(defn border-example [] + (let [frame (JFrame. "border example") pane (.getContentPane frame) ] + (add-components-to-pane pane) + (.pack frame) + (.setVisible frame true)))
martindemello/clojure-swing
6c55a2398ccb6541a47afe6a07cc6cf95212e9d6
top-level project README
diff --git a/README b/README new file mode 100644 index 0000000..ad2a9cb --- /dev/null +++ b/README @@ -0,0 +1 @@ +Clojure and Swing stuff
martindemello/clojure-swing
d8a84863cfd5a5155cc8545939c68306bbcda051
add a few hello-world slides
diff --git a/presentation/content/presentation/_helloworld.clj.txt b/presentation/content/presentation/_helloworld.clj.txt new file mode 100644 index 0000000..2e4cfe6 --- /dev/null +++ b/presentation/content/presentation/_helloworld.clj.txt @@ -0,0 +1,16 @@ +--- +filter: erb +--- + +<% uv :lang => "scheme", :theme => 'twilight' do -%> + +(ns hello + (:import (javax.swing JFrame))) + +(let [frame (JFrame.)] + (.setSize frame 200 100) + (.setDefaultCloseOperation frame JFrame/EXIT_ON_CLOSE) + (.setTitle frame "Hello World!") + (.setVisible frame true)) + +<% end -%> diff --git a/presentation/content/presentation/_helloworld.java.txt b/presentation/content/presentation/_helloworld.java.txt new file mode 100644 index 0000000..e7f3e2b --- /dev/null +++ b/presentation/content/presentation/_helloworld.java.txt @@ -0,0 +1,24 @@ +--- +filter: erb +--- + +<% uv :lang => "java", :theme => 'twilight' do -%> + + import javax.swing.JFrame; + + public class HelloFrame extends JFrame { + public static void main(String[] args) { + new HelloFrame(); + } + + public HelloFrame() { + this.setSize(200, 100); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setTitle("Hello World!"); + this.setVisible(true); + } + } + +<% end -%> + +Code from http://www.java2s.com/Code/Java/Swing-JFC/TheSwingVersionoftheHelloWorldProgram.htm diff --git a/presentation/content/presentation/index.txt b/presentation/content/presentation/index.txt index c07aa7a..6e37fcf 100644 --- a/presentation/content/presentation/index.txt +++ b/presentation/content/presentation/index.txt @@ -1,63 +1,46 @@ --- title: Webby S5 created_at: 2008-05-18 22:10:21.995012 -06:00 author: You company: Company copyright: Creative Commons filter: - erb - textile - slides layout: presentation --- -h1. Webby S5 Generator +h1. Clojure and Swing -Clever introductory text that will grab the audience's attention. +Using the Swing toolkit to write GUI desktop applications in Clojure +h1. Why Swing? -h1. Title of the First Slide +* Default java gui toolkit +* No native code needed +* Tons of documentation, examples and third-party widgets -A little more build up before really getting into the meat of it. +h1. Hello World +It doesn't take much to get a Swing GUI up and running: -h1. Title of the Second Slide +<% uv :lang => "scheme", :theme => 'twilight' do -%> +(import 'javax.swing.JOptionPane) -Finally, some code! - -<% uv :lang => "ragel", :theme => 'twilight' do -%> -action dgt { printf("DGT: %c\n", fc); } -action dec { printf("DEC: .\n"); } -action exp { printf("EXP: %c\n", fc); } -action exp_sign { printf("SGN: %c\n", fc); } -action number { /*NUMBER*/ } - -number = ( - [0-9]+ $dgt ( '.' @dec [0-9]+ $dgt )? - ( [eE] ( [+\-] $exp_sign )? [0-9]+ $exp )? -) %number; - -main := ( number '\n' )*; +(. JOptionPane (showMessageDialog nil "Hello World")) <% end -%> -h1. Title of the Third Slide - -This code comes from a partial +h1. Translating from Java -<%= render :partial => 'sample_code', :guard => true %> +An example from a Java Swing tutorial: +<%= render :partial => 'helloworld.java', :guard => true %> -h1. Title of the Fourth Slide - -A quadratic equation with real or complex coefficients has two (not necessarily distinct) solutions, called roots, which may or may not be real, given by the quadratic formula: - -<% tex2img 'quadratic', :path => 'images', :alt => 'quadratic', :resolution => '300x300' do -%> -x = \frac{-b\pm\sqrt[]{b^2-4ac}}{2a} -<% end -%> +h1. Translating from Java -h1. The Final Slide +And the same example in Clojure -And that about sums it up! +<%= render :partial => 'helloworld.clj', :guard => true %> -Thanks for visiting
martindemello/clojure-swing
ea0280ecfe51e8b8b5c1dd031f976fbfdfaffea2
added README
diff --git a/presentation/README b/presentation/README new file mode 100644 index 0000000..1af650d --- /dev/null +++ b/presentation/README @@ -0,0 +1,5 @@ +* Generate slideshow: + webby + +* View presentation: + open output/presentation/index.html
martindemello/clojure-swing
b1f48c6b82310daf08664d1785ad0fb70bd695c5
add a basepath so we can run this without a webserver
diff --git a/presentation/Sitefile b/presentation/Sitefile index 1debfbd..299f19e 100644 --- a/presentation/Sitefile +++ b/presentation/Sitefile @@ -1,10 +1,11 @@ - task :default => :build desc 'deploy the site to the webserver' task :deploy => [:build, 'deploy:rsync'] SITE.uv.theme = 'twilight' SITE.uv.line_numbers = false +SITE.base = ".." + # EOF diff --git a/presentation/layouts/presentation.txt b/presentation/layouts/presentation.txt index 7d83933..7b7be01 100644 --- a/presentation/layouts/presentation.txt +++ b/presentation/layouts/presentation.txt @@ -1,43 +1,44 @@ --- extension: html filter: - erb + - basepath --- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><%= h(@page.title) %></title> <meta name="author" content="<%= h(@page.author) %>" /> <meta name="company" content="<%= h(@page.company) %>" /> <!-- configuration parameters --> <meta name="defaultView" content="slideshow" /> <meta name="controlVis" content="hidden" /> <link rel="stylesheet" href="/presentation/s5/slides.css" type="text/css" media="projection" id="slideProj" /> <link rel="stylesheet" href="/presentation/s5/outline.css" type="text/css" media="screen" id="outlineStyle" /> <link rel="stylesheet" href="/css/uv/twilight.css" type="text/css" media="screen, projection" /> <!-- S5 JS --> <script src="/presentation/s5/slides.js" type="text/javascript"></script> </head> <body> <div class="layout"> <div id="controls"><!-- DO NOT EDIT --></div> <div id="currentSlide"><!-- DO NOT EDIT --></div> <div id="header"></div> <div id="footer"> <h2>Copyright &copy; <%= h(@page.copyright) %></h2> </div> </div> <div class="presentation"> <%= @content %> </div> </body> </html>
martindemello/clojure-swing
5108eecdf72473ef0e21e567cf77b5adf08232d1
webby-gen presentation
diff --git a/presentation/Sitefile b/presentation/Sitefile new file mode 100644 index 0000000..1debfbd --- /dev/null +++ b/presentation/Sitefile @@ -0,0 +1,10 @@ + +task :default => :build + +desc 'deploy the site to the webserver' +task :deploy => [:build, 'deploy:rsync'] + +SITE.uv.theme = 'twilight' +SITE.uv.line_numbers = false + +# EOF diff --git a/presentation/content/css/uv/twilight.css b/presentation/content/css/uv/twilight.css new file mode 100644 index 0000000..d6427dd --- /dev/null +++ b/presentation/content/css/uv/twilight.css @@ -0,0 +1,137 @@ +pre.twilight .DiffInserted { + background-color: #253B22; + color: #F8F8F8; +} +pre.twilight .DiffHeader { + background-color: #0E2231; + color: #F8F8F8; + font-style: italic; +} +pre.twilight .CssPropertyValue { + color: #F9EE98; +} +pre.twilight .CCCPreprocessorDirective { + color: #AFC4DB; +} +pre.twilight .Constant { + color: #CF6A4C; +} +pre.twilight .DiffChanged { + background-color: #4A410D; + color: #F8F8F8; +} +pre.twilight .EmbeddedSource { + background-color: #A3A6AD; +} +pre.twilight .Support { + color: #9B859D; +} +pre.twilight .MarkupList { + color: #F9EE98; +} +pre.twilight .CssConstructorArgument { + color: #8F9D6A; +} +pre.twilight .Storage { + color: #F9EE98; +} +pre.twilight .line-numbers { + background-color: inherit; + color: #999999; +} +pre.twilight .CssClass { + color: #9B703F; +} +pre.twilight .StringConstant { + color: #DDF2A4; +} +pre.twilight .CssAtRule { + color: #8693A5; +} +pre.twilight .MetaTagInline { + color: #E0C589; +} +pre.twilight .MarkupHeading { + color: #CF6A4C; +} +pre.twilight .CssTagName { + color: #CDA869; +} +pre.twilight .SupportConstant { + color: #CF6A4C; +} +pre.twilight .DiffDeleted { + background-color: #420E09; + color: #F8F8F8; +} +pre.twilight .CCCPreprocessorLine { + color: #8996A8; +} +pre.twilight .StringRegexpSpecial { + color: #CF7D34; +} +pre.twilight .EmbeddedSourceBright { + background-color: #9C9EA4; +} +pre.twilight .InvalidIllegal { + background-color: #241A24; + color: #F8F8F8; +} +pre.twilight .SupportFunction { + color: #DAD085; +} +pre.twilight .CssAdditionalConstants { + color: #CA7840; +} +pre.twilight .MetaTagAll { + color: #AC885B; +} +pre.twilight .StringRegexp { + color: #E9C062; +} +pre.twilight .StringEmbeddedSource { + color: #DAEFA3; +} +pre.twilight .EntityInheritedClass { + color: #9B5C2E; + font-style: italic; +} +pre.twilight .CssId { + color: #8B98AB; +} +pre.twilight .CssPseudoClass { + color: #8F9D6A; +} +pre.twilight .StringVariable { + color: #8A9A95; +} +pre.twilight .String { + color: #8F9D6A; +} +pre.twilight .Keyword { + color: #CDA869; +} +pre.twilight { + background-color: #141414; + color: #F8F8F8; +} +pre.twilight .CssPropertyName { + color: #C5AF75; +} +pre.twilight .DoctypeXmlProcessing { + color: #494949; +} +pre.twilight .InvalidDeprecated { + color: #D2A8A1; + font-style: italic; +} +pre.twilight .Variable { + color: #7587A6; +} +pre.twilight .Entity { + color: #9B703F; +} +pre.twilight .Comment { + color: #5F5A60; + font-style: italic; +} diff --git a/presentation/content/presentation/_sample_code.txt b/presentation/content/presentation/_sample_code.txt new file mode 100644 index 0000000..61976a0 --- /dev/null +++ b/presentation/content/presentation/_sample_code.txt @@ -0,0 +1,10 @@ +--- +filter: erb +--- +<% uv :lang => "ruby", :theme => 'twilight' do -%> +class A + def method() + puts "in class #{self.class.name}" + end +end +<% end -%> diff --git a/presentation/content/presentation/index.txt b/presentation/content/presentation/index.txt new file mode 100644 index 0000000..c07aa7a --- /dev/null +++ b/presentation/content/presentation/index.txt @@ -0,0 +1,63 @@ +--- +title: Webby S5 +created_at: 2008-05-18 22:10:21.995012 -06:00 +author: You +company: Company +copyright: Creative Commons +filter: + - erb + - textile + - slides +layout: presentation +--- +h1. Webby S5 Generator + +Clever introductory text that will grab the audience's attention. + + +h1. Title of the First Slide + +A little more build up before really getting into the meat of it. + + +h1. Title of the Second Slide + +Finally, some code! + +<% uv :lang => "ragel", :theme => 'twilight' do -%> +action dgt { printf("DGT: %c\n", fc); } +action dec { printf("DEC: .\n"); } +action exp { printf("EXP: %c\n", fc); } +action exp_sign { printf("SGN: %c\n", fc); } +action number { /*NUMBER*/ } + +number = ( + [0-9]+ $dgt ( '.' @dec [0-9]+ $dgt )? + ( [eE] ( [+\-] $exp_sign )? [0-9]+ $exp )? +) %number; + +main := ( number '\n' )*; +<% end -%> + + +h1. Title of the Third Slide + +This code comes from a partial + +<%= render :partial => 'sample_code', :guard => true %> + + +h1. Title of the Fourth Slide + +A quadratic equation with real or complex coefficients has two (not necessarily distinct) solutions, called roots, which may or may not be real, given by the quadratic formula: + +<% tex2img 'quadratic', :path => 'images', :alt => 'quadratic', :resolution => '300x300' do -%> +x = \frac{-b\pm\sqrt[]{b^2-4ac}}{2a} +<% end -%> + + +h1. The Final Slide + +And that about sums it up! + +Thanks for visiting diff --git a/presentation/content/presentation/s5/blank.gif b/presentation/content/presentation/s5/blank.gif new file mode 100644 index 0000000..75b945d Binary files /dev/null and b/presentation/content/presentation/s5/blank.gif differ diff --git a/presentation/content/presentation/s5/bodybg.gif b/presentation/content/presentation/s5/bodybg.gif new file mode 100644 index 0000000..5f448a1 Binary files /dev/null and b/presentation/content/presentation/s5/bodybg.gif differ diff --git a/presentation/content/presentation/s5/framing.css b/presentation/content/presentation/s5/framing.css new file mode 100644 index 0000000..14d8509 --- /dev/null +++ b/presentation/content/presentation/s5/framing.css @@ -0,0 +1,23 @@ +/* The following styles size, place, and layer the slide components. + Edit these if you want to change the overall slide layout. + The commented lines can be uncommented (and modified, if necessary) + to help you with the rearrangement process. */ + +/* target = 1024x768 */ + +div#header, div#footer, .slide {width: 100%; top: 0; left: 0;} +div#header {top: 0; height: 3em; z-index: 1;} +div#footer {top: auto; bottom: 0; height: 2.5em; z-index: 5;} +.slide {top: 0; width: 92%; padding: 3.5em 4% 4%; z-index: 2; list-style: none;} +div#controls {left: 50%; bottom: 0; width: 50%; z-index: 100;} +div#controls form {position: absolute; bottom: 0; right: 0; width: 100%; + margin: 0;} +#currentSlide {position: absolute; width: 10%; left: 45%; bottom: 1em; z-index: 10;} +html>body #currentSlide {position: fixed;} + +/* +div#header {background: #FCC;} +div#footer {background: #CCF;} +div#controls {background: #BBD;} +div#currentSlide {background: #FFC;} +*/ diff --git a/presentation/content/presentation/s5/iepngfix.htc b/presentation/content/presentation/s5/iepngfix.htc new file mode 100644 index 0000000..bba2db7 --- /dev/null +++ b/presentation/content/presentation/s5/iepngfix.htc @@ -0,0 +1,42 @@ +<public:component> +<public:attach event="onpropertychange" onevent="doFix()" /> + +<script> + +// IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull http://www.twinhelix.com +// Free usage permitted as long as this notice remains intact. + +// This must be a path to a blank image. That's all the configuration you need here. +var blankImg = 'ui/default/blank.gif'; + +var f = 'DXImageTransform.Microsoft.AlphaImageLoader'; + +function filt(s, m) { + if (filters[f]) { + filters[f].enabled = s ? true : false; + if (s) with (filters[f]) { src = s; sizingMethod = m } + } else if (s) style.filter = 'progid:'+f+'(src="'+s+'",sizingMethod="'+m+'")'; +} + +function doFix() { + if ((parseFloat(navigator.userAgent.match(/MSIE (\S+)/)[1]) < 5.5) || + (event && !/(background|src)/.test(event.propertyName))) return; + + if (tagName == 'IMG') { + if ((/\.png$/i).test(src)) { + filt(src, 'image'); // was 'scale' + src = blankImg; + } else if (src.indexOf(blankImg) < 0) filt(); + } else if (style.backgroundImage) { + if (style.backgroundImage.match(/^url[("']+(.*\.png)[)"']+$/i)) { + var s = RegExp.$1; + style.backgroundImage = ''; + filt(s, 'crop'); + } else filt(); + } +} + +doFix(); + +</script> +</public:component> \ No newline at end of file diff --git a/presentation/content/presentation/s5/opera.css b/presentation/content/presentation/s5/opera.css new file mode 100644 index 0000000..9e9d2a3 --- /dev/null +++ b/presentation/content/presentation/s5/opera.css @@ -0,0 +1,7 @@ +/* DO NOT CHANGE THESE unless you really want to break Opera Show */ +.slide { + visibility: visible !important; + position: static !important; + page-break-before: always; +} +#slide0 {page-break-before: avoid;} diff --git a/presentation/content/presentation/s5/outline.css b/presentation/content/presentation/s5/outline.css new file mode 100644 index 0000000..62db519 --- /dev/null +++ b/presentation/content/presentation/s5/outline.css @@ -0,0 +1,15 @@ +/* don't change this unless you want the layout stuff to show up in the outline view! */ + +.layout div, #footer *, #controlForm * {display: none;} +#footer, #controls, #controlForm, #navLinks, #toggle { + display: block; visibility: visible; margin: 0; padding: 0;} +#toggle {float: right; padding: 0.5em;} +html>body #toggle {position: fixed; top: 0; right: 0;} + +/* making the outline look pretty-ish */ + +#slide0 h1, #slide0 h2, #slide0 h3, #slide0 h4 {border: none; margin: 0;} +#slide0 h1 {padding-top: 1.5em;} +.slide h1 {margin: 1.5em 0 0; padding-top: 0.25em; + border-top: 1px solid #888; border-bottom: 1px solid #AAA;} +#toggle {border: 1px solid; border-width: 0 0 1px 1px; background: #FFF;} diff --git a/presentation/content/presentation/s5/pretty.css b/presentation/content/presentation/s5/pretty.css new file mode 100644 index 0000000..3d3acef --- /dev/null +++ b/presentation/content/presentation/s5/pretty.css @@ -0,0 +1,86 @@ +/* Following are the presentation styles -- edit away! */ + +body {background: #FFF url(bodybg.gif) -16px 0 no-repeat; color: #000; font-size: 2em;} +:link, :visited {text-decoration: none; color: #00C;} +#controls :active {color: #88A !important;} +#controls :focus {outline: 1px dotted #227;} +h1, h2, h3, h4 {font-size: 100%; margin: 0; padding: 0; font-weight: inherit;} +ul, pre {margin: 0; line-height: 1em;} +html, body {margin: 0; padding: 0;} + +blockquote, q {font-style: italic;} +blockquote {padding: 0 2em 0.5em; margin: 0 1.5em 0.5em; text-align: center; font-size: 1em;} +blockquote p {margin: 0;} +blockquote i {font-style: normal;} +blockquote b {display: block; margin-top: 0.5em; font-weight: normal; font-size: smaller; font-style: normal;} +blockquote b i {font-style: italic;} + +kbd {font-weight: bold; font-size: 1em;} +sup {font-size: smaller; line-height: 1px;} + +.slide code {padding: 2px 0.25em; font-weight: bold; color: #533;} +.slide code.bad, code del {color: red;} +.slide code.old {color: silver;} +.slide pre {padding: 0; margin: 0.25em 0 0.5em 0.5em; color: #533; font-size: 90%;} +.slide pre code {display: block;} +.slide ul {margin-left: 5%; margin-right: 7%; list-style: disc;} +.slide li {margin-top: 0.75em; margin-right: 0;} +.slide ul ul {line-height: 1;} +.slide ul ul li {margin: .2em; font-size: 85%; list-style: square;} +.slide img.leader {display: block; margin: 0 auto;} + +div#header, div#footer {background: #005; color: #AAB; + font-family: Verdana, Helvetica, sans-serif;} +div#header {background: #005 url(bodybg.gif) -16px 0 no-repeat; + line-height: 1px;} +div#footer {font-size: 0.5em; font-weight: bold; padding: 1em 0;} +#footer h1, #footer h2 {display: block; padding: 0 1em;} +#footer h2 {font-style: italic;} + +div.long {font-size: 0.75em;} +.slide h1 {position: absolute; top: 0.7em; left: 87px; z-index: 1; + margin: 0; padding: 0.3em 0 0 50px; white-space: nowrap; + font: bold 150%/1em Helvetica, sans-serif; text-transform: capitalize; + color: #DDE; background: #005;} +.slide h3 {font-size: 130%;} +h1 abbr {font-variant: small-caps;} + +div#controls {position: absolute; left: 50%; bottom: 0; + width: 50%; + text-align: right; font: bold 0.9em Verdana, Helvetica, sans-serif;} +html>body div#controls {position: fixed; padding: 0 0 1em 0; + top: auto;} +div#controls form {position: absolute; bottom: 0; right: 0; width: 100%; + margin: 0; padding: 0;} +#controls #navLinks a {padding: 0; margin: 0 0.5em; + background: #005; border: none; color: #779; + cursor: pointer;} +#controls #navList {height: 1em;} +#controls #navList #jumplist {position: absolute; bottom: 0; right: 0; background: #DDD; color: #227;} + +#currentSlide {text-align: center; font-size: 0.5em; color: #449;} + +#slide0 {padding-top: 3.5em; font-size: 90%;} +#slide0 h1 {position: static; margin: 1em 0 0; padding: 0; + font: bold 2em Helvetica, sans-serif; white-space: normal; + color: #000; background: transparent;} +#slide0 h2 {font: bold italic 1em Helvetica, sans-serif; margin: 0.25em;} +#slide0 h3 {margin-top: 1.5em; font-size: 1.5em;} +#slide0 h4 {margin-top: 0; font-size: 1em;} + +ul.urls {list-style: none; display: inline; margin: 0;} +.urls li {display: inline; margin: 0;} +.note {display: none;} +.external {border-bottom: 1px dotted gray;} +html>body .external {border-bottom: none;} +.external:after {content: " \274F"; font-size: smaller; color: #77B;} + +.incremental, .incremental *, .incremental *:after {color: #DDE; visibility: visible;} +img.incremental {visibility: hidden;} +.slide .current {color: #B02;} + + +/* diagnostics + +li:after {content: " [" attr(class) "]"; color: #F88;} + */ \ No newline at end of file diff --git a/presentation/content/presentation/s5/print.css b/presentation/content/presentation/s5/print.css new file mode 100644 index 0000000..458be69 --- /dev/null +++ b/presentation/content/presentation/s5/print.css @@ -0,0 +1,25 @@ +/* The following rule is necessary to have all slides appear in print! DO NOT REMOVE IT! */ +.slide, ul {page-break-inside: avoid; visibility: visible !important;} +h1 {page-break-after: avoid;} + +body {font-size: 12pt; background: white;} +* {color: black;} + +#slide0 h1 {font-size: 200%; border: none; margin: 0.5em 0 0.25em;} +#slide0 h3 {margin: 0; padding: 0;} +#slide0 h4 {margin: 0 0 0.5em; padding: 0;} +#slide0 {margin-bottom: 3em;} + +h1 {border-top: 2pt solid gray; border-bottom: 1px dotted silver;} +.extra {background: transparent !important;} +div.extra, pre.extra, .example {font-size: 10pt; color: #333;} +ul.extra a {font-weight: bold;} +p.example {display: none;} + +#header {display: none;} +#footer h1 {margin: 0; border-bottom: 1px solid; color: gray; font-style: italic;} +#footer h2, #controls {display: none;} + +/* The following rule keeps the layout stuff out of print. Remove at your own risk! */ +.layout, .layout * {display: none !important;} + diff --git a/presentation/content/presentation/s5/s5-core.css b/presentation/content/presentation/s5/s5-core.css new file mode 100644 index 0000000..86444e0 --- /dev/null +++ b/presentation/content/presentation/s5/s5-core.css @@ -0,0 +1,9 @@ +/* Do not edit or override these styles! The system will likely break if you do. */ + +div#header, div#footer, div#controls, .slide {position: absolute;} +html>body div#header, html>body div#footer, + html>body div#controls, html>body .slide {position: fixed;} +.handout {display: none;} +.layout {display: block;} +.slide, .hideme, .incremental {visibility: hidden;} +#slide0 {visibility: visible;} diff --git a/presentation/content/presentation/s5/slides.css b/presentation/content/presentation/s5/slides.css new file mode 100644 index 0000000..0786d7d --- /dev/null +++ b/presentation/content/presentation/s5/slides.css @@ -0,0 +1,3 @@ +@import url(s5-core.css); /* required to make the slide show run at all */ +@import url(framing.css); /* sets basic placement and size of slide components */ +@import url(pretty.css); /* stuff that makes the slides look better than blah */ \ No newline at end of file diff --git a/presentation/content/presentation/s5/slides.js b/presentation/content/presentation/s5/slides.js new file mode 100644 index 0000000..38fe853 --- /dev/null +++ b/presentation/content/presentation/s5/slides.js @@ -0,0 +1,553 @@ +// S5 v1.1 slides.js -- released into the Public Domain +// +// Please see http://www.meyerweb.com/eric/tools/s5/credits.html for information +// about all the wonderful and talented contributors to this code! + +var undef; +var slideCSS = ''; +var snum = 0; +var smax = 1; +var incpos = 0; +var number = undef; +var s5mode = true; +var defaultView = 'slideshow'; +var controlVis = 'visible'; + +var isIE = navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') < 1 ? 1 : 0; +var isOp = navigator.userAgent.indexOf('Opera') > -1 ? 1 : 0; +var isGe = navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Safari') < 1 ? 1 : 0; + +function hasClass(object, className) { + if (!object.className) return false; + return (object.className.search('(^|\\s)' + className + '(\\s|$)') != -1); +} + +function hasValue(object, value) { + if (!object) return false; + return (object.search('(^|\\s)' + value + '(\\s|$)') != -1); +} + +function removeClass(object,className) { + if (!object) return; + object.className = object.className.replace(new RegExp('(^|\\s)'+className+'(\\s|$)'), RegExp.$1+RegExp.$2); +} + +function addClass(object,className) { + if (!object || hasClass(object, className)) return; + if (object.className) { + object.className += ' '+className; + } else { + object.className = className; + } +} + +function GetElementsWithClassName(elementName,className) { + var allElements = document.getElementsByTagName(elementName); + var elemColl = new Array(); + for (var i = 0; i< allElements.length; i++) { + if (hasClass(allElements[i], className)) { + elemColl[elemColl.length] = allElements[i]; + } + } + return elemColl; +} + +function isParentOrSelf(element, id) { + if (element == null || element.nodeName=='BODY') return false; + else if (element.id == id) return true; + else return isParentOrSelf(element.parentNode, id); +} + +function nodeValue(node) { + var result = ""; + if (node.nodeType == 1) { + var children = node.childNodes; + for (var i = 0; i < children.length; ++i) { + result += nodeValue(children[i]); + } + } + else if (node.nodeType == 3) { + result = node.nodeValue; + } + return(result); +} + +function slideLabel() { + var slideColl = GetElementsWithClassName('*','slide'); + var list = document.getElementById('jumplist'); + smax = slideColl.length; + for (var n = 0; n < smax; n++) { + var obj = slideColl[n]; + + var did = 'slide' + n.toString(); + obj.setAttribute('id',did); + if (isOp) continue; + + var otext = ''; + var menu = obj.firstChild; + if (!menu) continue; // to cope with empty slides + while (menu && menu.nodeType == 3) { + menu = menu.nextSibling; + } + if (!menu) continue; // to cope with slides with only text nodes + + var menunodes = menu.childNodes; + for (var o = 0; o < menunodes.length; o++) { + otext += nodeValue(menunodes[o]); + } + list.options[list.length] = new Option(n + ' : ' + otext, n); + } +} + +function currentSlide() { + var cs; + if (document.getElementById) { + cs = document.getElementById('currentSlide'); + } else { + cs = document.currentSlide; + } + cs.innerHTML = '<span id="csHere">' + snum + '<\/span> ' + + '<span id="csSep">\/<\/span> ' + + '<span id="csTotal">' + (smax-1) + '<\/span>'; + if (snum == 0) { + cs.style.visibility = 'hidden'; + } else { + cs.style.visibility = 'visible'; + } +} + +function go(step) { + if (document.getElementById('slideProj').disabled || step == 0) return; + var jl = document.getElementById('jumplist'); + var cid = 'slide' + snum; + var ce = document.getElementById(cid); + if (incrementals[snum].length > 0) { + for (var i = 0; i < incrementals[snum].length; i++) { + removeClass(incrementals[snum][i], 'current'); + removeClass(incrementals[snum][i], 'incremental'); + } + } + if (step != 'j') { + snum += step; + lmax = smax - 1; + if (snum > lmax) snum = lmax; + if (snum < 0) snum = 0; + } else + snum = parseInt(jl.value); + var nid = 'slide' + snum; + var ne = document.getElementById(nid); + if (!ne) { + ne = document.getElementById('slide0'); + snum = 0; + } + if (step < 0) {incpos = incrementals[snum].length} else {incpos = 0;} + if (incrementals[snum].length > 0 && incpos == 0) { + for (var i = 0; i < incrementals[snum].length; i++) { + if (hasClass(incrementals[snum][i], 'current')) + incpos = i + 1; + else + addClass(incrementals[snum][i], 'incremental'); + } + } + if (incrementals[snum].length > 0 && incpos > 0) + addClass(incrementals[snum][incpos - 1], 'current'); + ce.style.visibility = 'hidden'; + ne.style.visibility = 'visible'; + jl.selectedIndex = snum; + currentSlide(); + number = 0; +} + +function goTo(target) { + if (target >= smax || target == snum) return; + go(target - snum); +} + +function subgo(step) { + if (step > 0) { + removeClass(incrementals[snum][incpos - 1],'current'); + removeClass(incrementals[snum][incpos], 'incremental'); + addClass(incrementals[snum][incpos],'current'); + incpos++; + } else { + incpos--; + removeClass(incrementals[snum][incpos],'current'); + addClass(incrementals[snum][incpos], 'incremental'); + addClass(incrementals[snum][incpos - 1],'current'); + } +} + +function toggle() { + var slideColl = GetElementsWithClassName('*','slide'); + var slides = document.getElementById('slideProj'); + var outline = document.getElementById('outlineStyle'); + if (!slides.disabled) { + slides.disabled = true; + outline.disabled = false; + s5mode = false; + fontSize('1em'); + for (var n = 0; n < smax; n++) { + var slide = slideColl[n]; + slide.style.visibility = 'visible'; + } + } else { + slides.disabled = false; + outline.disabled = true; + s5mode = true; + fontScale(); + for (var n = 0; n < smax; n++) { + var slide = slideColl[n]; + slide.style.visibility = 'hidden'; + } + slideColl[snum].style.visibility = 'visible'; + } +} + +function showHide(action) { + var obj = GetElementsWithClassName('*','hideme')[0]; + switch (action) { + case 's': obj.style.visibility = 'visible'; break; + case 'h': obj.style.visibility = 'hidden'; break; + case 'k': + if (obj.style.visibility != 'visible') { + obj.style.visibility = 'visible'; + } else { + obj.style.visibility = 'hidden'; + } + break; + } +} + +// 'keys' code adapted from MozPoint (http://mozpoint.mozdev.org/) +function keys(key) { + if (!key) { + key = event; + key.which = key.keyCode; + } + if (key.which == 84) { + toggle(); + return; + } + if (s5mode) { + switch (key.which) { + case 10: // return + case 13: // enter + if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; + if (key.target && isParentOrSelf(key.target, 'controls')) return; + if(number != undef) { + goTo(number); + break; + } + case 32: // spacebar + case 34: // page down + case 39: // rightkey + case 40: // downkey + if(number != undef) { + go(number); + } else if (!incrementals[snum] || incpos >= incrementals[snum].length) { + go(1); + } else { + subgo(1); + } + break; + case 33: // page up + case 37: // leftkey + case 38: // upkey + if(number != undef) { + go(-1 * number); + } else if (!incrementals[snum] || incpos <= 0) { + go(-1); + } else { + subgo(-1); + } + break; + case 36: // home + goTo(0); + break; + case 35: // end + goTo(smax-1); + break; + case 67: // c + showHide('k'); + break; + } + if (key.which < 48 || key.which > 57) { + number = undef; + } else { + if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; + if (key.target && isParentOrSelf(key.target, 'controls')) return; + number = (((number != undef) ? number : 0) * 10) + (key.which - 48); + } + } + return false; +} + +function clicker(e) { + number = undef; + var target; + if (window.event) { + target = window.event.srcElement; + e = window.event; + } else target = e.target; + if (target.getAttribute('href') != null || hasValue(target.rel, 'external') || isParentOrSelf(target, 'controls') || isParentOrSelf(target,'embed') || isParentOrSelf(target,'object')) return true; + if (!e.which || e.which == 1) { + if (!incrementals[snum] || incpos >= incrementals[snum].length) { + go(1); + } else { + subgo(1); + } + } +} + +function findSlide(hash) { + var target = null; + var slides = GetElementsWithClassName('*','slide'); + for (var i = 0; i < slides.length; i++) { + var targetSlide = slides[i]; + if ( (targetSlide.name && targetSlide.name == hash) + || (targetSlide.id && targetSlide.id == hash) ) { + target = targetSlide; + break; + } + } + while(target != null && target.nodeName != 'BODY') { + if (hasClass(target, 'slide')) { + return parseInt(target.id.slice(5)); + } + target = target.parentNode; + } + return null; +} + +function slideJump() { + if (window.location.hash == null) return; + var sregex = /^#slide(\d+)$/; + var matches = sregex.exec(window.location.hash); + var dest = null; + if (matches != null) { + dest = parseInt(matches[1]); + } else { + dest = findSlide(window.location.hash.slice(1)); + } + if (dest != null) + go(dest - snum); +} + +function fixLinks() { + var thisUri = window.location.href; + thisUri = thisUri.slice(0, thisUri.length - window.location.hash.length); + var aelements = document.getElementsByTagName('A'); + for (var i = 0; i < aelements.length; i++) { + var a = aelements[i].href; + var slideID = a.match('\#slide[0-9]{1,2}'); + if ((slideID) && (slideID[0].slice(0,1) == '#')) { + var dest = findSlide(slideID[0].slice(1)); + if (dest != null) { + if (aelements[i].addEventListener) { + aelements[i].addEventListener("click", new Function("e", + "if (document.getElementById('slideProj').disabled) return;" + + "go("+dest+" - snum); " + + "if (e.preventDefault) e.preventDefault();"), true); + } else if (aelements[i].attachEvent) { + aelements[i].attachEvent("onclick", new Function("", + "if (document.getElementById('slideProj').disabled) return;" + + "go("+dest+" - snum); " + + "event.returnValue = false;")); + } + } + } + } +} + +function externalLinks() { + if (!document.getElementsByTagName) return; + var anchors = document.getElementsByTagName('a'); + for (var i=0; i<anchors.length; i++) { + var anchor = anchors[i]; + if (anchor.getAttribute('href') && hasValue(anchor.rel, 'external')) { + anchor.target = '_blank'; + addClass(anchor,'external'); + } + } +} + +function createControls() { + var controlsDiv = document.getElementById("controls"); + if (!controlsDiv) return; + var hider = ' onmouseover="showHide(\'s\');" onmouseout="showHide(\'h\');"'; + var hideDiv, hideList = ''; + if (controlVis == 'hidden') { + hideDiv = hider; + } else { + hideList = hider; + } + controlsDiv.innerHTML = '<form action="#" id="controlForm"' + hideDiv + '>' + + '<div id="navLinks">' + + '<a accesskey="t" id="toggle" href="javascript:toggle();">&#216;<\/a>' + + '<a accesskey="z" id="prev" href="javascript:go(-1);">&laquo;<\/a>' + + '<a accesskey="x" id="next" href="javascript:go(1);">&raquo;<\/a>' + + '<div id="navList"' + hideList + '><select id="jumplist" onchange="go(\'j\');"><\/select><\/div>' + + '<\/div><\/form>'; + if (controlVis == 'hidden') { + var hidden = document.getElementById('navLinks'); + } else { + var hidden = document.getElementById('jumplist'); + } + addClass(hidden,'hideme'); +} + +function fontScale() { // causes layout problems in FireFox that get fixed if browser's Reload is used; same may be true of other Gecko-based browsers + if (!s5mode) return false; + var vScale = 22; // both yield 32 (after rounding) at 1024x768 + var hScale = 32; // perhaps should auto-calculate based on theme's declared value? + if (window.innerHeight) { + var vSize = window.innerHeight; + var hSize = window.innerWidth; + } else if (document.documentElement.clientHeight) { + var vSize = document.documentElement.clientHeight; + var hSize = document.documentElement.clientWidth; + } else if (document.body.clientHeight) { + var vSize = document.body.clientHeight; + var hSize = document.body.clientWidth; + } else { + var vSize = 700; // assuming 1024x768, minus chrome and such + var hSize = 1024; // these do not account for kiosk mode or Opera Show + } + var newSize = Math.min(Math.round(vSize/vScale),Math.round(hSize/hScale)); + fontSize(newSize + 'px'); + if (isGe) { // hack to counter incremental reflow bugs + var obj = document.getElementsByTagName('body')[0]; + obj.style.display = 'none'; + obj.style.display = 'block'; + } +} + +function fontSize(value) { + if (!(s5ss = document.getElementById('s5ss'))) { + if (!isIE) { + document.getElementsByTagName('head')[0].appendChild(s5ss = document.createElement('style')); + s5ss.setAttribute('media','screen, projection'); + s5ss.setAttribute('id','s5ss'); + } else { + document.createStyleSheet(); + document.s5ss = document.styleSheets[document.styleSheets.length - 1]; + } + } + if (!isIE) { + while (s5ss.lastChild) s5ss.removeChild(s5ss.lastChild); + s5ss.appendChild(document.createTextNode('body {font-size: ' + value + ' !important;}')); + } else { + document.s5ss.addRule('body','font-size: ' + value + ' !important;'); + } +} + +function notOperaFix() { + slideCSS = document.getElementById('slideProj').href; + var slides = document.getElementById('slideProj'); + var outline = document.getElementById('outlineStyle'); + slides.setAttribute('media','screen'); + outline.disabled = true; + if (isGe) { + slides.setAttribute('href','null'); // Gecko fix + slides.setAttribute('href',slideCSS); // Gecko fix + } + if (isIE && document.styleSheets && document.styleSheets[0]) { + document.styleSheets[0].addRule('img', 'behavior: url(ui/default/iepngfix.htc)'); + document.styleSheets[0].addRule('div', 'behavior: url(ui/default/iepngfix.htc)'); + document.styleSheets[0].addRule('.slide', 'behavior: url(ui/default/iepngfix.htc)'); + } +} + +function getIncrementals(obj) { + var incrementals = new Array(); + if (!obj) + return incrementals; + var children = obj.childNodes; + for (var i = 0; i < children.length; i++) { + var child = children[i]; + if (hasClass(child, 'incremental')) { + if (child.nodeName == 'OL' || child.nodeName == 'UL') { + removeClass(child, 'incremental'); + for (var j = 0; j < child.childNodes.length; j++) { + if (child.childNodes[j].nodeType == 1) { + addClass(child.childNodes[j], 'incremental'); + } + } + } else { + incrementals[incrementals.length] = child; + removeClass(child,'incremental'); + } + } + if (hasClass(child, 'show-first')) { + if (child.nodeName == 'OL' || child.nodeName == 'UL') { + removeClass(child, 'show-first'); + if (child.childNodes[isGe].nodeType == 1) { + removeClass(child.childNodes[isGe], 'incremental'); + } + } else { + incrementals[incrementals.length] = child; + } + } + incrementals = incrementals.concat(getIncrementals(child)); + } + return incrementals; +} + +function createIncrementals() { + var incrementals = new Array(); + for (var i = 0; i < smax; i++) { + incrementals[i] = getIncrementals(document.getElementById('slide'+i)); + } + return incrementals; +} + +function defaultCheck() { + var allMetas = document.getElementsByTagName('meta'); + for (var i = 0; i< allMetas.length; i++) { + if (allMetas[i].name == 'defaultView') { + defaultView = allMetas[i].content; + } + if (allMetas[i].name == 'controlVis') { + controlVis = allMetas[i].content; + } + } +} + +// Key trap fix, new function body for trap() +function trap(e) { + if (!e) { + e = event; + e.which = e.keyCode; + } + try { + modifierKey = e.ctrlKey || e.altKey || e.metaKey; + } + catch(e) { + modifierKey = false; + } + return modifierKey || e.which == 0; +} + +function startup() { + defaultCheck(); + if (!isOp) + createControls(); + slideLabel(); + fixLinks(); + externalLinks(); + fontScale(); + if (!isOp) { + notOperaFix(); + incrementals = createIncrementals(); + slideJump(); + if (defaultView == 'outline') { + toggle(); + } + document.onkeyup = keys; + document.onkeypress = trap; + document.onclick = clicker; + } +} + +window.onload = startup; +window.onresize = function(){setTimeout('fontScale()', 50);} \ No newline at end of file diff --git a/presentation/layouts/presentation.txt b/presentation/layouts/presentation.txt new file mode 100644 index 0000000..7d83933 --- /dev/null +++ b/presentation/layouts/presentation.txt @@ -0,0 +1,43 @@ +--- +extension: html +filter: + - erb +--- +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title><%= h(@page.title) %></title> + <meta name="author" content="<%= h(@page.author) %>" /> + <meta name="company" content="<%= h(@page.company) %>" /> + + <!-- configuration parameters --> + <meta name="defaultView" content="slideshow" /> + <meta name="controlVis" content="hidden" /> + + <link rel="stylesheet" href="/presentation/s5/slides.css" type="text/css" media="projection" id="slideProj" /> + <link rel="stylesheet" href="/presentation/s5/outline.css" type="text/css" media="screen" id="outlineStyle" /> + <link rel="stylesheet" href="/css/uv/twilight.css" type="text/css" media="screen, projection" /> + + <!-- S5 JS --> + <script src="/presentation/s5/slides.js" type="text/javascript"></script> +</head> +<body> + +<div class="layout"> + <div id="controls"><!-- DO NOT EDIT --></div> + <div id="currentSlide"><!-- DO NOT EDIT --></div> + <div id="header"></div> + <div id="footer"> + <h2>Copyright &copy; <%= h(@page.copyright) %></h2> + </div> +</div> + +<div class="presentation"> + <%= @content %> +</div> + +</body> +</html> diff --git a/presentation/templates/_code_partial.erb b/presentation/templates/_code_partial.erb new file mode 100644 index 0000000..bb8dc6c --- /dev/null +++ b/presentation/templates/_code_partial.erb @@ -0,0 +1,13 @@ +--- +filter: erb +--- +<%% uv :lang => 'ruby', :line_numbers => false, :theme => 'twilight' do -%> +# This is a sample of Ruby code +# +class Object + def returning( obj, &block ) + block.call obj + return obj + end +end +<%% end -%> diff --git a/presentation/templates/presentation.erb b/presentation/templates/presentation.erb new file mode 100644 index 0000000..b554221 --- /dev/null +++ b/presentation/templates/presentation.erb @@ -0,0 +1,40 @@ +--- +title: <%= title %> +created_at: <%= Time.now.to_y %> +author: You +company: Company +copyright: Creative Commons +filter: + - erb + - textile + - slides +layout: presentation +--- +h1. Presentation Title + +Clever introductory text that will grab the audience's attention. + + +h1. Title of the First Slide + +A little more build up before really getting into the meat of it. + + +h1. Title of the Second Slide + +Finally, some code! + +<%% uv :lang => 'ruby', :line_numbers => false do -%> +class EnglishMajor + def supercilious + 'behaving or looking as though one thinks one is superior to others' + end +end +<%% end -%> + + +h1. The Final Slide + +And that about sums it up! + +Thanks for visiting
pc2/liftracc
1cdfca41a11fd5fa5a661767e6a0aea176aa379d
modifications for linpack testing
diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 26dcee3..d5949f6 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -1,67 +1,77 @@ cmake_minimum_required(VERSION 2.6.4) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) project(benchmarks) find_package(LIFTRACC REQUIRED) include(${LIFTRACC_USE_FILE}) find_package(BLAS REQUIRED) find_package(CBLAS REQUIRED) find_package(Goto2) include_directories( ${BLAS_INCLUDE_DIRS} ${CBLAS_INCLUDE_DIRS} ${GOTO2_INCLUDE_DIRS} ) link_directories( ${BLAS_LIBRARY_DIR} ${CBLAS_LIBRARY_DIR} ${GOTO2_LIBRARY_DIR} ) add_executable(linpack-new ${PROJECT_SOURCE_DIR}/src/linpack-new.c ) target_link_libraries(linpack-new m ) add_executable(linpack-new-mod ${PROJECT_SOURCE_DIR}/src/linpack-new-mod.c ) target_link_libraries(linpack-new-mod m ) add_executable(linpack-liftracc ${PROJECT_SOURCE_DIR}/src/linpack-liftracc.c ) target_link_libraries(linpack-liftracc liftracc - cblas - blas ) +add_executable(linpack-testing + ${PROJECT_SOURCE_DIR}/src/linpack-testing.c +) + +target_link_libraries(linpack-testing + liftracc +) + +set(LIFTRACC_TESTING_SELECT "cblas" CACHE STRING "Options: cblas, liftracc.") +string(TOUPPER "${LIFTRACC_TESTING_SELECT}" SELECT_VALUE) +add_definitions(-D_SELECT_${SELECT_VALUE}_) + add_custom_command( TARGET linpack-liftracc POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${PROJECT_SOURCE_DIR}/src/linpack-liftracc.sh ${PROJECT_BINARY_DIR}/linpack-liftracc.sh COMMENT "copy linpack-liftracc.sh" ) add_executable(linpack-cblas ${PROJECT_SOURCE_DIR}/src/linpack-cblas.c ) target_link_libraries(linpack-cblas cblas blas ) diff --git a/benchmarks/profiling/plot.py b/benchmarks/profiling/plot.py index 83578c3..0829c1d 100755 --- a/benchmarks/profiling/plot.py +++ b/benchmarks/profiling/plot.py @@ -1,128 +1,140 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- from matplotlib import * use('PDF') rcParams['text.usetex']=True rcParams['text.latex.unicode']=True rcParams['font.family']='serif' import csv import sys import numpy as npy import matplotlib.pyplot as plt import matplotlib.mlab as mlab import pylab from math import sqrt from decimal import Decimal as d class tps: calc = d(2261000000) av = d(2268881244) class DataClass: def __init__(self): self.label = r'no\_label' self.sym = '-' self.data_dict = {} self.data_count_dict = {} self.xrange = [] self.data = [] def count(list): return d(len(list)) def calc_mean(list): return d(sum(list)/count(list)) def calc_confi(val, list): n = count(list) mean = calc_mean(list) tmp = [ d((d(x) - mean)**2) for x in list ] std_abw = d(d(1/n)*sum(tmp)).sqrt() # maximum like-lihood std_err = d(std_abw / n.sqrt()) return val * std_err def read_data(file_name, conv_sec, sym=None, label=None): print "Processing", file_name csv_file = csv.reader(open(file_name), delimiter = ' ', skipinitialspace = True) dc = DataClass() if sym: dc.sym=sym if label: dc.label=label av_error = 0 for row in csv_file: if len(row) and not row[0].startswith('#'): print row[0], row[6] if dc.data_dict.has_key(int(row[0])): old = dc.data_dict[int(row[0])] else: old = 0 if dc.data_count_dict.has_key(int(row[0])): count = dc.data_count_dict[int(row[0])] else: count = 0 dc.data_dict[int(row[0])] = int((old*count)+int(row[0])/(count+1)) dc.data_count_dict[int(row[0])] = count+1 for key in sorted(dc.data_dict.keys()): dc.xrange.append(d(key)) dc.data.append(d(dc.data_dict[key])) #for row in csv_file: # if row[0].find("measuring_error") > -1: # num_row = [ d(x) for x in row[3:] ] # av_error = calc_mean(num_row) # av_confi = calc_confi(d("1.96"), num_row) # #print "Average Error:", av_error, "(", av_error-av_confi, ",", av_error+av_confi, ")" # break #for row in csv_file: # if row[0].find("measuring_error") == -1: # num_row = [ d(x) for x in row ] # num_row[3:] = [ d(x-av_error) for x in num_row[3:]] # num_row_sec = [ d((x-av_error)/d(conv_sec)) for x in num_row[3:]] # dc.xrange.append(2**num_row[0]) # dc.data_tks.append(num_row[3:]) # dc.mean_tks.append(calc_mean(num_row[3:])) # dc.confi_tks.append(calc_confi(d("1.96"), num_row[3:])) # dc.data_sec.append(num_row_sec) # dc.mean_sec.append(calc_mean(num_row_sec)) # dc.confi_sec.append(calc_confi(d("1.96"), num_row_sec)) return dc def plot_graph(filename, data, title, x_label, y_label, x_lim=None, y_lim=None): print "Plotting to", filename pylab.figure() for d in data: pylab.plot(d.xrange, d.data, d.sym, ms=5, label=d.label, linewidth=1) #pylab.errorbar(d.xrange, d.mean_sec, d.confi_sec, label=d.label, xerr=None, # fmt=d.sym, elinewidth=3, ms=5, capsize=6) pylab.legend(loc=0) pylab.xlabel(x_label, fontsize=12) pylab.ylabel(y_label, fontsize=12) pylab.xscale('log', basex=2) pylab.yscale('log', basey=10) if x_lim: pylab.xlim(x_lim) if y_lim: pylab.ylim(y_lim) pylab.title(title, fontsize=12) pylab.grid('on', '.') pylab.savefig(filename) if __name__ == "__main__": lpn_new = read_data('linpack_new_200-4096.txt', tps.av, sym='-o', label=r'lpn\_new') lpn_mod = read_data('linpack_new_mod_16-16384.txt', tps.av, sym='-s', label=r'lpn\_mod') lpl_atl = read_data('linpack_liftracc_atlas_16-16384.txt', tps.av, sym='-o', label=r'lpl\_atl') lpl_cbl = read_data('linpack_liftracc_cblas_16-16384.txt', tps.av, sym='->', label=r'lpl\_cbl') lpl_cle = read_data('linpack_liftracc_clear_16-16384.txt', tps.av, sym='-D', label=r'lpl\_cle') lpl_cub = read_data('linpack_liftracc_cublas_16-16384.txt', tps.av, sym='-v', label=r'lpl\_cub') lpl_go2 = read_data('linpack_liftracc_goto2_16-16384.txt', tps.av, sym='-s', label=r'lpl\_go2') plot_graph('test', [lpn_new, lpn_mod, lpl_atl, lpl_cbl, lpl_cle, lpl_cub, lpl_go2], r'Test', r'Dimension [n]', r'KFLOPS', x_lim=(2**3,2**15) ) + nlp_cblas = read_data('new_linpack_cblas.txt', tps.av, sym='-o', label=r'nlp\_cblas') + nlp_pre = read_data('new_linpack_ldpreload.txt', tps.av, sym='-s', label=r'nlp\_pre') + nlp_lift = read_data('new_linpack_liftracc.txt', tps.av, sym='-o', label=r'nlp\_lift') + nlp_new = read_data('new_linpack_new.txt', tps.av, sym='->', label=r'nlp\_new') + + plot_graph('test2', + [nlp_cblas, nlp_pre, nlp_lift, nlp_new], + r'Test', + r'Dimension [n]', + r'KFLOPS', x_lim=(2**3,2**15) + ) + diff --git a/benchmarks/src/linpack-testing.c b/benchmarks/src/linpack-testing.c new file mode 100644 index 0000000..04d1d8e --- /dev/null +++ b/benchmarks/src/linpack-testing.c @@ -0,0 +1,277 @@ +/* +** +** LINPACK.C Linpack benchmark, calculates FLOPS. +** (FLoating Point Operations Per Second) +** +** Translated to C by Bonnie Toy 5/88 +** +** Modified by Will Menninger, 10/93, with these features: +** (modified on 2/25/94 to fix a problem with daxpy for +** unequal increments or equal increments not equal to 1. +** Jack Dongarra) +** +** Modified by Manuel Niekamp <niekma@upb.de> +** (modified on 19.11.2010) +** +** To compile: +** gcc -O3 -I<liftracc_incdir> -L<liftracc_libdir> -lliftracc -o linpack linpack.c +** +*/ +#include <stdio.h> +#include <stdlib.h> +#include <math.h> +#include <time.h> + +#define ZERO 0.0e0 +#define ONE 1.0e0 + +/* CBLAS selected */ +#if defined(_SELECT_CBLAS_) + +#include "cblas.h" +const char *info_str = "cblas version"; +#define call_idamax cblas_idamax +#define call_dscal cblas_dscal +#define call_daxpy cblas_daxpy +#define call_ddot cblas_ddot + +/* LIFTRACC selected */ +#elif defined(_SELECT_LIFTRACC_) + +#include "liftracc.h" +const char *info_str = "liftracc version"; +#define call_idamax liftracc_idamax +#define call_dscal liftracc_dscal +#define call_daxpy liftracc_daxpy +#define call_ddot liftracc_ddot + +/* nothing selected */ +#else + +#error "No compiler option -D_SELECT_(CBLAS|LIFTRACC)_ found." +#define call_idamax no_idamax +#define call_dscal no_dscal +#define call_daxpy no_daxpy +#define call_ddot no_ddot + +#endif + +static double linpack_dyn(long nreps, int arsize); +static void matgen_dyn(double *a, int lda, int n, double *b, double *norma); +static void dgefa_dyn(double *a, int lda, int n, int *ipvt, int *info); +static void dgesl_dyn(double *a, int lda, int n, int *ipvt, double *b, int job); +static double second(void); + +static void print_mempool(void *mempool, int ar2dsize, int arsize, int intsize); + +static void *mempool; + +#define MAX_DIM 16384 + +int main(void) +{ + char buf[80]; + int arsize; + long arsize2d, memreq, nreps; + size_t malloc_arg; + + printf("\n\nUsing %s.\n\n", info_str); + printf("Average performance:\n"); + printf("N Reps Time(s) DGEFA DGESL OVERHEAD KFLOPS\n"); + printf("------------------------------------------\n"); + + for (arsize=16; arsize<=MAX_DIM; arsize*=2) { + arsize/=2; + arsize*=2; + arsize2d = (long)arsize*(long)arsize; + memreq=arsize2d*sizeof(double)+(long)arsize*sizeof(double)+(long)arsize*sizeof(int); + malloc_arg=(size_t)memreq; + if (malloc_arg!=memreq || (mempool=malloc(malloc_arg))==NULL) { + printf("Not enough memory available for given array size.\n\n"); + return 1; + } + nreps=1; + while (linpack_dyn(nreps, arsize)<10.) + nreps*=2; + /* print mempool array */ + print_mempool(mempool, arsize2d*sizeof(double), (long)arsize*sizeof(double), (long)arsize*sizeof(int)); + free(mempool); + } +} + +static double linpack_dyn(long nreps, int arsize) +{ + double *a, *b; + double norma, t1, kflops, tdgesl, tdgefa, totalt, toverhead, ops; + int *ipvt, n, info, lda; + long i, arsize2d; + + lda = arsize; + n = arsize/2; + arsize2d = (long)arsize*(long)arsize; + ops=((2.0*n*n*n)/3.0+2.0*n*n); + a=(double *)mempool; + b=a+arsize2d; + ipvt=(int *)&b[arsize]; + tdgesl=0; + tdgefa=0; + totalt=second(); + for (i=0; i<nreps; i++) { + matgen_dyn(a, lda, n, b, &norma); + t1 = second(); + dgefa_dyn(a, lda, n, ipvt, &info); + tdgefa += second()-t1; + t1 = second(); + dgesl_dyn(a, lda, n, ipvt, b, 0); + tdgesl += second()-t1; + } + totalt=second()-totalt; + if (totalt<0.5 || tdgefa+tdgesl<0.2) + return(0.); + kflops=2.*nreps*ops/(1000.*(tdgefa+tdgesl)); + toverhead=totalt-tdgefa-tdgesl; + if (tdgefa<0.) tdgefa=0.; + if (tdgesl<0.) tdgesl=0.; + if (toverhead<0.) toverhead=0.; + printf("%d %ld %.2f %.2f%% %.2f%% %.2f%% %.3f\n", + arsize, nreps, totalt, 100.*tdgefa/totalt, + 100.*tdgesl/totalt, 100.*toverhead/totalt, + kflops); + + return(totalt); +} + +static void matgen_dyn(double *a, int lda, int n, double *b, double *norma) +{ + int init, i, j; + + init = 1325; + *norma = 0.0; + for (j = 0; j < n; j++) + for (i = 0; i < n; i++) { + init = (int)((long)3125*(long)init % 65536L); + a[lda*j+i] = (init - 32768.0)/16384.0; + *norma = (a[lda*j+i] > *norma) ? a[lda*j+i] : *norma; + } + for (i = 0; i < n; i++) + b[i] = 0.0; + for (j = 0; j < n; j++) + for (i = 0; i < n; i++) + b[i] = b[i] + a[lda*j+i]; + + printf("Matrix A:\n"); + for (j=0; j<n; j++) + for (i=0; i<n; i++) + printf("%f ", a[lda*j+i]); + printf("\n"); + + printf("Matrix B:\n"); + for (j=0; j<n; j++) + for (i=0; i<n; i++) + printf("%f ", b[lda*j+i]); + printf("\n"); +} + +static void dgefa_dyn(double *a, int lda, int n, int *ipvt, int *info) +{ + double t; + int j, k, kp1, l, nm1; + + /* gaussian elimination with partial pivoting */ + *info = 0; + nm1 = n - 1; + if (nm1 >= 0) + for (k = 0; k < nm1; k++) { + kp1 = k + 1; + /* find l = pivot index */ + l = call_idamax(n-k,&a[lda*k+k],1) + k; + ipvt[k] = l; + /* zero pivot implies this column already triangularized */ + if (a[lda*k+l] != ZERO) { + /* interchange if necessary */ + if (l != k) { + t = a[lda*k+l]; + a[lda*k+l] = a[lda*k+k]; + a[lda*k+k] = t; + } + /* compute multipliers */ + t = -ONE/a[lda*k+k]; + call_dscal(n-(k+1),t,&a[lda*k+k+1],1); + /* row elimination with column indexing */ + for (j = kp1; j < n; j++) { + t = a[lda*j+l]; + if (l != k) { + a[lda*j+l] = a[lda*j+k]; + a[lda*j+k] = t; + } + call_daxpy(n-(k+1),t,&a[lda*k+k+1],1,&a[lda*j+k+1],1); + } + } else + (*info) = k; + } + ipvt[n-1] = n-1; + if (a[lda*(n-1)+(n-1)] == ZERO) + (*info) = n-1; +} + +static void dgesl_dyn(double *a, int lda, int n, int *ipvt, double *b, int job) +{ + double t; + int k, kb, l, nm1; + + nm1 = n - 1; + if (job == 0) { + /* job = 0 , solve a * x = b */ + /* first solve l*y = b */ + if (nm1 >= 1) + for (k = 0; k < nm1; k++) { + l = ipvt[k]; + t = b[l]; + if (l != k) { + b[l] = b[k]; + b[k] = t; + } + call_daxpy(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); + } + /* now solve u*x = y */ + for (kb = 0; kb < n; kb++) { + k = n - (kb + 1); + b[k] = b[k]/a[lda*k+k]; + t = -b[k]; + call_daxpy(k,t,&a[lda*k+0],1,&b[0],1); + } + } else { + /* job = nonzero, solve trans(a) * x = b */ + /* first solve trans(u)*y = b */ + for (k = 0; k < n; k++) { + t = call_ddot(k,&a[lda*k+0],1,&b[0],1); + b[k] = (b[k] - t)/a[lda*k+k]; + } + /* now solve trans(l)*x = y */ + if (nm1 >= 1) + for (kb = 1; kb < nm1; kb++) { + k = n - (kb+1); + b[k] = b[k] + call_ddot(n-(k+1),&a[lda*k+k+1],1,&b[k+1],1); + l = ipvt[k]; + if (l != k) { + t = b[l]; + b[l] = b[k]; + b[k] = t; + } + } + } +} + +static double second(void) +{ + return ((double)((double)clock()/(double)CLOCKS_PER_SEC)); +} + +static void print_mempool(void *mempool, int ar2dsize, int arsize, int intsize) +{ + /* TODO */ + double *a = (double*)mempool; + double *b = (double*)a+ar2dsize; + double *c = (double*)b+arsize; +} + diff --git a/library/src/liftracc_testing.c b/library/src/liftracc_testing.c index f373f1e..703faaa 100644 --- a/library/src/liftracc_testing.c +++ b/library/src/liftracc_testing.c @@ -1,417 +1,434 @@ /** * @file liftracc_testing.c * @brief C file to test new functionality * * @author Manuel Niekamp <niekma@upb.de> * @version 0.1 * * This file implements the main functionality of the library. * It is intended to use this file for testing purpose. * If the here implemented code works and is tested it can * be easily transfered to the xsl file to auto generate the * complete library. */ #include "liftracc.h" #include "liftracc_logging.h" #include "liftracc_selector.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" extern profiling_data_t liftracc_function_profiling_data[]; #endif liftracc_selector_problem_info_t pinfo = { }; float liftracc_sdsdot(const int n, const float alpha, const float *x, const int incx, const float *y, const int incy) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_SDSDOT])); #endif /* _LIFTRACC_PROFILING_ */ float (*liftracc_plugin_func)(); float ret = 0.0; #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_SDSDOT, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_sdsdot"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { ret = (*liftracc_plugin_func)(n, alpha, x, incx, y, incy); } else ERROR("liftracc_sdsdot not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_SDSDOT])); #endif /* _LIFTRACC_PROFILING_ */ return ret; } float liftracc_sdsdot_(const int *n, const float *alpha, const float *x, const int *incx, const float *y, const int *incy) { return liftracc_sdsdot(*n, *alpha, x, *incx, y, *incy); } double liftracc_dsdot(const int n, const float *x, const int incx, const float *y, const int incy) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DSDOT])); #endif // _LIFTRACC_PROFILING_ double (*liftracc_plugin_func)(); double ret = 0.0; #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_DSDOT, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_dsdot"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { ret = (*liftracc_plugin_func)(n, x, incx, y, incy); } else ERROR("liftracc_dsdot not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DSDOT])); #endif /* _LIFTRACC_PROFILING_ */ return ret; } double liftracc_dsdot_(const int *n, const float *x, const int *incx, const float *y, const int *incy) { return liftracc_dsdot(*n, x, *incx, y, *incy); } float liftracc_sdot(const int n, const float *x, const int incx, const float *y, const int incy) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_SDOT])); #endif /* _LIFTRACC_PROFILING_ */ float (*liftracc_plugin_func)(); float ret = 0.0; #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_SDOT, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_sdot"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { ret = (*liftracc_plugin_func)(n, x, incx, y, incy); } else ERROR("liftracc_sdot not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_SDOT])); #endif /* _LIFTRACC_PROFILING_ */ return ret; } float liftracc_sdot_(const int *n, const float *x, const int *incx, const float *y, const int *incy) { return liftracc_sdot(*n, x, *incx, y, *incy); } liftracc_index_t liftracc_idamax(const int n, const double *x, const int incx) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ liftracc_index_t (*liftracc_plugin_func)(); liftracc_index_t ret = 0.0; #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_IDAMAX, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_idamax"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { ret = (*liftracc_plugin_func)(n, x, incx); } else ERROR("liftracc_idamax not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ return ret; } liftracc_index_t liftracc_idamax_(const int *n, const double *x, const int *incx) { return liftracc_idamax(*n, x, *incx); } void liftracc_dscal(const int n, const double alpha, double * x, const int incx) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ void (*liftracc_plugin_func)(); #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_DSCAL, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_dscal"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { (*liftracc_plugin_func)(n, alpha, x, incx); } else ERROR("liftracc_dscal not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ } void liftracc_dscal_(const int *n, const double *alpha, double *x, const int *incx) { liftracc_dscal(*n, *alpha, x, *incx); } void liftracc_daxpy(const int n, const double alpha, const double *x, const int incx, double *y, const int incy) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ void (*liftracc_plugin_func)(); #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_DAXPY, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_daxpy"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { (*liftracc_plugin_func)(n, alpha, x, incx, y, incy); } else ERROR("liftracc_daxpy not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ } void liftracc_daxpy_(const int *n, const double *alpha, const double *x, const int *incx, double *y, const int *incy) { liftracc_daxpy(*n, *alpha, x, *incx, y, *incy); } double liftracc_ddot(const int n, const double *x, const int incx, const double *y, const int incy) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ double (*liftracc_plugin_func)(); double ret = 0.0; #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = n; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_DDOT, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_ddot"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { ret = (*liftracc_plugin_func)(n, x, incx, y, incy); } else ERROR("liftracc_ddot not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ return ret; } double liftracc_ddot_(const int *n, const double *x, const int *incx, const double *y, const int *incy) { return liftracc_ddot(*n, x, *incx, y, *incy); } void liftracc_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc) { #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_start(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ + printf("LIFTRACC_DGEMM_USED\n"); + void (*liftracc_plugin_func)(); #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_start(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_SELECTOR_NEW_ pinfo.info1 = m; *(void **) (&liftracc_plugin_func) = liftracc_selector_select(SELECT_DGEMM, &pinfo); #else *(void **) (&liftracc_plugin_func) = liftracc_selector_select("liftracc_plugin_dgemm"); #endif /* _LIFTRACC_SELECTOR_NEW_ */ #if _LIFTRACC_PROFILING_ == 2 liftracc_function_timing_stop(&(liftracc_profiling_data[SELECT_CALL])); #endif /* _LIFTRACC_PROFILING_ */ if (liftracc_plugin_func != 0) { (*liftracc_plugin_func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } else ERROR("liftracc_dgemm not executed"); #if _LIFTRACC_PROFILING_ == 1 liftracc_function_timing_stop(&(liftracc_function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ } void liftracc_dgemm_(const char *transa, const char *transb, const int *m, const int *n, const int *k, const double *alpha, const double *a, const int *lda, const double *b, const int *ldb, const double *beta, double *c, const int *ldc) { liftracc_transpose_t ta, tb; switch (*transa) { case 'N': case 'n': ta = liftracc_no_trans; break; case 'T': case 't': ta = liftracc_trans; break; case 'C': case 'c': ta = liftracc_conj_trans; break; default: ta = liftracc_no_trans; break; } switch (*transb) { case 'N': case 'n': tb = liftracc_no_trans; break; case 'T': case 't': tb = liftracc_trans; break; case 'C': case 'c': tb = liftracc_conj_trans; break; default: tb = liftracc_no_trans; break; } liftracc_dgemm(liftracc_col_major, ta, tb, *m, *n, *k, *alpha, a, *lda, b, *ldb, *beta, c, *ldc); } -/* CBLAS interface */ -/* -__typeof__ (liftracc_dgemm_) cblas_dgemm __attribute__ ((alias("liftracc_dgemm"))); -*/ - -/* MKL interface */ -/* -__typeof__ (liftracc_dgemm_) dgemm_ __attribute__ ((alias("liftracc_dgemm_"))); -*/ +#ifdef _LIFTRACC_CBLAS_INTERFACE_ +__typeof__ (liftracc_sdsdot) cblas_sdsdot __attribute__ ((alias("liftracc_sdsdot"))); +__typeof__ (liftracc_dsdot) cblas_dsdot __attribute__ ((alias("liftracc_dsdot"))); +__typeof__ (liftracc_sdot) cblas_sdot __attribute__ ((alias("liftracc_sdot"))); +__typeof__ (liftracc_idamax) cblas_idamax __attribute__ ((alias("liftracc_idamax"))); +__typeof__ (liftracc_dscal) cblas_dscal __attribute__ ((alias("liftracc_dscal"))); +__typeof__ (liftracc_daxpy) cblas_daxpy __attribute__ ((alias("liftracc_daxpy"))); +__typeof__ (liftracc_ddot) cblas_ddot __attribute__ ((alias("liftracc_ddot"))); +__typeof__ (liftracc_dgemm) cblas_dgemm __attribute__ ((alias("liftracc_dgemm"))); + +__typeof__ (liftracc_sdsdot) f2c_sdsdot __attribute__ ((alias("liftracc_sdsdot"))); +__typeof__ (liftracc_dsdot) f2c_dsdot __attribute__ ((alias("liftracc_dsdot"))); +__typeof__ (liftracc_sdot) f2c_sdot __attribute__ ((alias("liftracc_sdot"))); +__typeof__ (liftracc_idamax) f2c_idamax __attribute__ ((alias("liftracc_idamax"))); +__typeof__ (liftracc_dscal) f2c_dscal __attribute__ ((alias("liftracc_dscal"))); +__typeof__ (liftracc_daxpy) f2c_daxpy __attribute__ ((alias("liftracc_daxpy"))); +__typeof__ (liftracc_ddot) f2c_ddot __attribute__ ((alias("liftracc_ddot"))); +__typeof__ (liftracc_dgemm) f2c_dgemm __attribute__ ((alias("liftracc_dgemm"))); +#endif // _LIFTRACC_CBLAS_INTERFACE_ + +#ifdef _LIFTRACC_MKL_INTERFACE_ +__typeof__ (liftracc_dgemm_) DGEMM __attribute__ ((alias("liftracc_dgemm_"))); +__typeof__ (liftracc_dgemm_) dgemm __attribute__ ((alias("liftracc_dgemm_"))); +#endif // _LIFTRACC_MKL_INTERFACE_
pc2/liftracc
fcdaec195e40740db478170d03eddf4f7c3f0a05
- fixed some bugs
diff --git a/benchmarks/src/linpack-cblas.c b/benchmarks/src/linpack-cblas.c index 85f747b..c03c003 100644 --- a/benchmarks/src/linpack-cblas.c +++ b/benchmarks/src/linpack-cblas.c @@ -1,341 +1,347 @@ /* ** ** LINPACK.C Linpack benchmark, calculates FLOPS. ** (FLoating Point Operations Per Second) ** ** Translated to C by Bonnie Toy 5/88 ** ** Modified by Will Menninger, 10/93, with these features: ** (modified on 2/25/94 to fix a problem with daxpy for ** unequal increments or equal increments not equal to 1. ** Jack Dongarra) ** ** Modified by Manuel Niekamp <niekma@upb.de> ** (modified on 06.02.2010 to direct calls through ** liftracc wrapper-library) ** ** To compile: ** gcc -O3 -I<liftracc_incdir> -L<liftracc_libdir> -lliftracc -o linpack linpack.c ** */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define ZERO 0.0e0 #define ONE 1.0e0 #include "cblas.h" +/* only testing */ +#define cblas_idamax inner_cblas_idamax +#define cblas_dscal inner_cblas_dscal +#define cblas_daxpy inner_cblas_daxpy +#define cblas_ddot inner_cblas_ddot + static double linpack_dyn(long nreps, int arsize); static void matgen_dyn(double *a, int lda, int n, double *b, double *norma); static void dgefa_dyn(double *a, int lda, int n, int *ipvt, int *info); static void dgesl_dyn(double *a, int lda, int n, int *ipvt, double *b, int job); static double second(void); static void *mempool; -#define MAX_DIM 1024 +#define MAX_DIM 8192 int main(void) { char buf[80]; int arsize; long arsize2d, memreq, nreps; size_t malloc_arg; printf("Average performance:\n\n"); printf("N Reps Time(s) DGEFA DGESL OVERHEAD KFLOPS\n"); printf("------------------------------------------\n"); - for (arsize=2; arsize<=MAX_DIM; arsize+=2) { + for (arsize=16; arsize<=MAX_DIM; arsize*=2) { arsize/=2; arsize*=2; arsize2d = (long)arsize*(long)arsize; memreq=arsize2d*sizeof(double)+(long)arsize*sizeof(double)+(long)arsize*sizeof(int); malloc_arg=(size_t)memreq; if (malloc_arg!=memreq || (mempool=malloc(malloc_arg))==NULL) { printf("Not enough memory available for given array size.\n\n"); return 1; } nreps=1; while (linpack_dyn(nreps, arsize)<10.) nreps*=2; free(mempool); } } static double linpack_dyn(long nreps, int arsize) { double *a, *b; double norma, t1, kflops, tdgesl, tdgefa, totalt, toverhead, ops; int *ipvt, n, info, lda; long i, arsize2d; lda = arsize; n = arsize/2; arsize2d = (long)arsize*(long)arsize; ops=((2.0*n*n*n)/3.0+2.0*n*n); a=(double *)mempool; b=a+arsize2d; ipvt=(int *)&b[arsize]; tdgesl=0; tdgefa=0; totalt=second(); for (i=0; i<nreps; i++) { matgen_dyn(a, lda, n, b, &norma); t1 = second(); dgefa_dyn(a, lda, n, ipvt, &info); tdgefa += second()-t1; t1 = second(); dgesl_dyn(a, lda, n, ipvt, b, 0); tdgesl += second()-t1; } totalt=second()-totalt; if (totalt<0.5 || tdgefa+tdgesl<0.2) return(0.); kflops=2.*nreps*ops/(1000.*(tdgefa+tdgesl)); toverhead=totalt-tdgefa-tdgesl; if (tdgefa<0.) tdgefa=0.; if (tdgesl<0.) tdgesl=0.; if (toverhead<0.) toverhead=0.; printf("%d %ld %.2f %.2f%% %.2f%% %.2f%% %.3f\n", arsize, nreps, totalt, 100.*tdgefa/totalt, 100.*tdgesl/totalt, 100.*toverhead/totalt, kflops); return(totalt); } /* ** For matgen, ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. */ static void matgen_dyn(double *a, int lda, int n, double *b, double *norma) { int init, i, j; init = 1325; *norma = 0.0; for (j = 0; j < n; j++) for (i = 0; i < n; i++) { init = (int)((long)3125*(long)init % 65536L); a[lda*j+i] = (init - 32768.0)/16384.0; *norma = (a[lda*j+i] > *norma) ? a[lda*j+i] : *norma; } for (i = 0; i < n; i++) b[i] = 0.0; for (j = 0; j < n; j++) for (i = 0; i < n; i++) b[i] = b[i] + a[lda*j+i]; } /* ** ** DGEFA benchmark ** ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. ** ** dgefa factors a double precision matrix by gaussian elimination. ** ** dgefa is usually called by dgeco, but it can be called ** directly with a saving in time if rcond is not needed. ** (time for dgeco) = (1 + 9/n)*(time for dgefa) . ** ** on entry ** ** a REAL precision[n][lda] ** the matrix to be factored. ** ** lda integer ** the leading dimension of the array a . ** ** n integer ** the order of the matrix a . ** ** on return ** ** a an upper triangular matrix and the multipliers ** which were used to obtain it. ** the factorization can be written a = l*u where ** l is a product of permutation and unit lower ** triangular matrices and u is upper triangular. ** ** ipvt integer[n] ** an integer vector of pivot indices. ** ** info integer ** = 0 normal value. ** = k if u[k][k] .eq. 0.0 . this is not an error ** condition for this subroutine, but it does ** indicate that dgesl or dgedi will divide by zero ** if called. use rcond in dgeco for a reliable ** indication of singularity. ** ** linpack. this version dated 08/14/78 . ** cleve moler, university of New Mexico, argonne national lab. ** ** functions ** ** blas daxpy, dscal, idamax ** */ static void dgefa_dyn(double *a, int lda, int n, int *ipvt, int *info) { double t; int j, k, kp1, l, nm1; /* gaussian elimination with partial pivoting */ *info = 0; nm1 = n - 1; if (nm1 >= 0) for (k = 0; k < nm1; k++) { kp1 = k + 1; /* find l = pivot index */ l = cblas_idamax(n-k,&a[lda*k+k],1) + k; ipvt[k] = l; /* zero pivot implies this column already triangularized */ if (a[lda*k+l] != ZERO) { /* interchange if necessary */ if (l != k) { t = a[lda*k+l]; a[lda*k+l] = a[lda*k+k]; a[lda*k+k] = t; } /* compute multipliers */ t = -ONE/a[lda*k+k]; cblas_dscal(n-(k+1),t,&a[lda*k+k+1],1); /* row elimination with column indexing */ for (j = kp1; j < n; j++) { t = a[lda*j+l]; if (l != k) { a[lda*j+l] = a[lda*j+k]; a[lda*j+k] = t; } cblas_daxpy(n-(k+1),t,&a[lda*k+k+1],1,&a[lda*j+k+1],1); } } else (*info) = k; } ipvt[n-1] = n-1; if (a[lda*(n-1)+(n-1)] == ZERO) (*info) = n-1; } /* ** ** DGESL benchmark ** ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. ** ** dgesl solves the double precision system ** a * x = b or trans(a) * x = b ** using the factors computed by dgeco or dgefa. ** ** on entry ** ** a double precision[n][lda] ** the output from dgeco or dgefa. ** ** lda integer ** the leading dimension of the array a . ** ** n integer ** the order of the matrix a . ** ** ipvt integer[n] ** the pivot vector from dgeco or dgefa. ** ** b double precision[n] ** the right hand side vector. ** ** job integer ** = 0 to solve a*x = b , ** = nonzero to solve trans(a)*x = b where ** trans(a) is the transpose. ** ** on return ** ** b the solution vector x . ** ** error condition ** ** a division by zero will occur if the input factor contains a ** zero on the diagonal. technically this indicates singularity ** but it is often caused by improper arguments or improper ** setting of lda . it will not occur if the subroutines are ** called correctly and if dgeco has set rcond .gt. 0.0 ** or dgefa has set info .eq. 0 . ** ** to compute inverse(a) * c where c is a matrix ** with p columns ** dgeco(a,lda,n,ipvt,rcond,z) ** if (!rcond is too small){ ** for (j=0,j<p,j++) ** dgesl(a,lda,n,ipvt,c[j][0],0); ** } ** ** linpack. this version dated 08/14/78 . ** cleve moler, university of new mexico, argonne national lab. ** ** functions ** ** blas daxpy, ddot */ static void dgesl_dyn(double *a, int lda, int n, int *ipvt, double *b, int job) { double t; int k, kb, l, nm1; nm1 = n - 1; if (job == 0) { /* job = 0 , solve a * x = b */ /* first solve l*y = b */ if (nm1 >= 1) for (k = 0; k < nm1; k++) { l = ipvt[k]; t = b[l]; if (l != k) { b[l] = b[k]; b[k] = t; } cblas_daxpy(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); } /* now solve u*x = y */ for (kb = 0; kb < n; kb++) { k = n - (kb + 1); b[k] = b[k]/a[lda*k+k]; t = -b[k]; cblas_daxpy(k,t,&a[lda*k+0],1,&b[0],1); } } else { /* job = nonzero, solve trans(a) * x = b */ /* first solve trans(u)*y = b */ for (k = 0; k < n; k++) { t = cblas_ddot(k,&a[lda*k+0],1,&b[0],1); b[k] = (b[k] - t)/a[lda*k+k]; } /* now solve trans(l)*x = y */ if (nm1 >= 1) for (kb = 1; kb < nm1; kb++) { k = n - (kb+1); b[k] = b[k] + cblas_ddot(n-(k+1),&a[lda*k+k+1],1,&b[k+1],1); l = ipvt[k]; if (l != k) { t = b[l]; b[l] = b[k]; b[k] = t; } } } } static double second(void) { return ((double)((double)clock()/(double)CLOCKS_PER_SEC)); } diff --git a/benchmarks/src/linpack-new-mod.c b/benchmarks/src/linpack-new-mod.c index 96453e6..20c16ea 100644 --- a/benchmarks/src/linpack-new-mod.c +++ b/benchmarks/src/linpack-new-mod.c @@ -1,597 +1,597 @@ /* ** ** LINPACK.C Linpack benchmark, calculates FLOPS. ** (FLoating Point Operations Per Second) ** ** Translated to C by Bonnie Toy 5/88 ** ** Modified by Will Menninger, 10/93, with these features: ** (modified on 2/25/94 to fix a problem with daxpy for ** unequal increments or equal increments not equal to 1. ** Jack Dongarra) ** ** - Defaults to double precision. ** - Averages ROLLed and UNROLLed performance. ** - User selectable array sizes. ** - Automatically does enough repetitions to take at least 10 CPU seconds. ** - Prints machine precision. ** - ANSI prototyping. ** ** Modified by Manuel Niekamp <niekma@upb.de> ** (modified on 07.02.2010 run from dim 2 to ** MAX_DIM) ** ** To compile: cc -O -o linpack linpack.c -lm ** */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <float.h> #define DP #ifdef SP #define ZERO 0.0 #define ONE 1.0 #define PREC "Single" #define BASE10DIG FLT_DIG typedef float REAL; #endif #ifdef DP #define ZERO 0.0e0 #define ONE 1.0e0 #define PREC "Double" #define BASE10DIG DBL_DIG typedef double REAL; #endif static REAL linpack (long nreps,int arsize); static void matgen (REAL *a,int lda,int n,REAL *b,REAL *norma); static void dgefa (REAL *a,int lda,int n,int *ipvt,int *info,int roll); static void dgesl (REAL *a,int lda,int n,int *ipvt,REAL *b,int job,int roll); static void daxpy_r (int n,REAL da,REAL *dx,int incx,REAL *dy,int incy); static REAL ddot_r (int n,REAL *dx,int incx,REAL *dy,int incy); static void dscal_r (int n,REAL da,REAL *dx,int incx); static void daxpy_ur (int n,REAL da,REAL *dx,int incx,REAL *dy,int incy); static REAL ddot_ur (int n,REAL *dx,int incx,REAL *dy,int incy); static void dscal_ur (int n,REAL da,REAL *dx,int incx); static int idamax (int n,REAL *dx,int incx); static REAL second (void); static void *mempool; #define MAX_DIM 16384 int main(void) { char buf[80]; int arsize; long arsize2d,memreq,nreps; size_t malloc_arg; printf("\n\nLINPACK benchmark, %s precision.\n",PREC); printf("Machine precision: %d digits.\n",BASE10DIG); printf("Average rolled and unrolled performance:\n\n"); printf("N Reps Time(s) DGEFA DGESL OVERHEAD KFLOPS\n"); printf("------------------------------------------\n"); - for (arsize=8192; arsize<=MAX_DIM; arsize*=2) { + for (arsize=10; arsize<=MAX_DIM; arsize*=2) { arsize/=2; arsize*=2; arsize2d = (long)arsize*(long)arsize; memreq=arsize2d*sizeof(REAL)+(long)arsize*sizeof(REAL)+(long)arsize*sizeof(int); malloc_arg=(size_t)memreq; if (malloc_arg!=memreq || (mempool=malloc(malloc_arg))==NULL) { printf("Not enough memory available for given array size.\n\n"); continue; } nreps=1; while (linpack(nreps,arsize)<10.) nreps*=2; free(mempool); } return 0; } static REAL linpack(long nreps,int arsize) { REAL *a,*b; REAL norma,t1,kflops,tdgesl,tdgefa,totalt,toverhead,ops; int *ipvt,n,info,lda; long i,arsize2d; lda = arsize; n = arsize/2; arsize2d = (long)arsize*(long)arsize; ops=((2.0*n*n*n)/3.0+2.0*n*n); a=(REAL *)mempool; b=a+arsize2d; ipvt=(int *)&b[arsize]; tdgesl=0; tdgefa=0; totalt=second(); for (i=0;i<nreps;i++) { matgen(a,lda,n,b,&norma); t1 = second(); dgefa(a,lda,n,ipvt,&info,1); tdgefa += second()-t1; t1 = second(); dgesl(a,lda,n,ipvt,b,0,1); tdgesl += second()-t1; } for (i=0;i<nreps;i++) { matgen(a,lda,n,b,&norma); t1 = second(); dgefa(a,lda,n,ipvt,&info,0); tdgefa += second()-t1; t1 = second(); dgesl(a,lda,n,ipvt,b,0,0); tdgesl += second()-t1; } totalt=second()-totalt; if (totalt<0.5 || tdgefa+tdgesl<0.2) return(0.); kflops=2.*nreps*ops/(1000.*(tdgefa+tdgesl)); toverhead=totalt-tdgefa-tdgesl; if (tdgefa<0.) tdgefa=0.; if (tdgesl<0.) tdgesl=0.; if (toverhead<0.) toverhead=0.; printf("%d %ld %.2f %.2f%% %.2f%% %.2f%% %.3f\n", arsize, nreps, totalt, 100.*tdgefa/totalt, 100.*tdgesl/totalt, 100.*toverhead/totalt, kflops); return(totalt); } /* ** For matgen, ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. */ static void matgen(REAL *a,int lda,int n,REAL *b,REAL *norma) { int init,i,j; init = 1325; *norma = 0.0; for (j = 0; j < n; j++) for (i = 0; i < n; i++) { init = (int)((long)3125*(long)init % 65536L); a[lda*j+i] = (init - 32768.0)/16384.0; *norma = (a[lda*j+i] > *norma) ? a[lda*j+i] : *norma; } for (i = 0; i < n; i++) b[i] = 0.0; for (j = 0; j < n; j++) for (i = 0; i < n; i++) b[i] = b[i] + a[lda*j+i]; } /* ** ** DGEFA benchmark ** ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. ** ** dgefa factors a double precision matrix by gaussian elimination. ** ** dgefa is usually called by dgeco, but it can be called ** directly with a saving in time if rcond is not needed. ** (time for dgeco) = (1 + 9/n)*(time for dgefa) . ** ** on entry ** ** a REAL precision[n][lda] ** the matrix to be factored. ** ** lda integer ** the leading dimension of the array a . ** ** n integer ** the order of the matrix a . ** ** on return ** ** a an upper triangular matrix and the multipliers ** which were used to obtain it. ** the factorization can be written a = l*u where ** l is a product of permutation and unit lower ** triangular matrices and u is upper triangular. ** ** ipvt integer[n] ** an integer vector of pivot indices. ** ** info integer ** = 0 normal value. ** = k if u[k][k] .eq. 0.0 . this is not an error ** condition for this subroutine, but it does ** indicate that dgesl or dgedi will divide by zero ** if called. use rcond in dgeco for a reliable ** indication of singularity. ** ** linpack. this version dated 08/14/78 . ** cleve moler, university of New Mexico, argonne national lab. ** ** functions ** ** blas daxpy,dscal,idamax ** */ static void dgefa(REAL *a,int lda,int n,int *ipvt,int *info,int roll) { REAL t; int idamax(),j,k,kp1,l,nm1; /* gaussian elimination with partial pivoting */ if (roll) { *info = 0; nm1 = n - 1; if (nm1 >= 0) for (k = 0; k < nm1; k++) { kp1 = k + 1; /* find l = pivot index */ l = idamax(n-k,&a[lda*k+k],1) + k; ipvt[k] = l; /* zero pivot implies this column already triangularized */ if (a[lda*k+l] != ZERO) { /* interchange if necessary */ if (l != k) { t = a[lda*k+l]; a[lda*k+l] = a[lda*k+k]; a[lda*k+k] = t; } /* compute multipliers */ t = -ONE/a[lda*k+k]; dscal_r(n-(k+1),t,&a[lda*k+k+1],1); /* row elimination with column indexing */ for (j = kp1; j < n; j++) { t = a[lda*j+l]; if (l != k) { a[lda*j+l] = a[lda*j+k]; a[lda*j+k] = t; } daxpy_r(n-(k+1),t,&a[lda*k+k+1],1,&a[lda*j+k+1],1); } } else (*info) = k; } ipvt[n-1] = n-1; if (a[lda*(n-1)+(n-1)] == ZERO) (*info) = n-1; } else { *info = 0; nm1 = n - 1; if (nm1 >= 0) for (k = 0; k < nm1; k++) { kp1 = k + 1; /* find l = pivot index */ l = idamax(n-k,&a[lda*k+k],1) + k; ipvt[k] = l; /* zero pivot implies this column already triangularized */ if (a[lda*k+l] != ZERO) { /* interchange if necessary */ if (l != k) { t = a[lda*k+l]; a[lda*k+l] = a[lda*k+k]; a[lda*k+k] = t; } /* compute multipliers */ t = -ONE/a[lda*k+k]; dscal_ur(n-(k+1),t,&a[lda*k+k+1],1); /* row elimination with column indexing */ for (j = kp1; j < n; j++) { t = a[lda*j+l]; if (l != k) { a[lda*j+l] = a[lda*j+k]; a[lda*j+k] = t; } daxpy_ur(n-(k+1),t,&a[lda*k+k+1],1,&a[lda*j+k+1],1); } } else (*info) = k; } ipvt[n-1] = n-1; if (a[lda*(n-1)+(n-1)] == ZERO) (*info) = n-1; } } /* ** ** DGESL benchmark ** ** We would like to declare a[][lda], but c does not allow it. In this ** function, references to a[i][j] are written a[lda*i+j]. ** ** dgesl solves the double precision system ** a * x = b or trans(a) * x = b ** using the factors computed by dgeco or dgefa. ** ** on entry ** ** a double precision[n][lda] ** the output from dgeco or dgefa. ** ** lda integer ** the leading dimension of the array a . ** ** n integer ** the order of the matrix a . ** ** ipvt integer[n] ** the pivot vector from dgeco or dgefa. ** ** b double precision[n] ** the right hand side vector. ** ** job integer ** = 0 to solve a*x = b , ** = nonzero to solve trans(a)*x = b where ** trans(a) is the transpose. ** ** on return ** ** b the solution vector x . ** ** error condition ** ** a division by zero will occur if the input factor contains a ** zero on the diagonal. technically this indicates singularity ** but it is often caused by improper arguments or improper ** setting of lda . it will not occur if the subroutines are ** called correctly and if dgeco has set rcond .gt. 0.0 ** or dgefa has set info .eq. 0 . ** ** to compute inverse(a) * c where c is a matrix ** with p columns ** dgeco(a,lda,n,ipvt,rcond,z) ** if (!rcond is too small){ ** for (j=0,j<p,j++) ** dgesl(a,lda,n,ipvt,c[j][0],0); ** } ** ** linpack. this version dated 08/14/78 . ** cleve moler, university of new mexico, argonne national lab. ** ** functions ** ** blas daxpy,ddot */ static void dgesl(REAL *a,int lda,int n,int *ipvt,REAL *b,int job,int roll) { REAL t; int k,kb,l,nm1; if (roll) { nm1 = n - 1; if (job == 0) { /* job = 0 , solve a * x = b */ /* first solve l*y = b */ if (nm1 >= 1) for (k = 0; k < nm1; k++) { l = ipvt[k]; t = b[l]; if (l != k) { b[l] = b[k]; b[k] = t; } daxpy_r(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); } /* now solve u*x = y */ for (kb = 0; kb < n; kb++) { k = n - (kb + 1); b[k] = b[k]/a[lda*k+k]; t = -b[k]; daxpy_r(k,t,&a[lda*k+0],1,&b[0],1); } } else { /* job = nonzero, solve trans(a) * x = b */ /* first solve trans(u)*y = b */ for (k = 0; k < n; k++) { t = ddot_r(k,&a[lda*k+0],1,&b[0],1); b[k] = (b[k] - t)/a[lda*k+k]; } /* now solve trans(l)*x = y */ if (nm1 >= 1) for (kb = 1; kb < nm1; kb++) { k = n - (kb+1); b[k] = b[k] + ddot_r(n-(k+1),&a[lda*k+k+1],1,&b[k+1],1); l = ipvt[k]; if (l != k) { t = b[l]; b[l] = b[k]; b[k] = t; } } } } else { nm1 = n - 1; if (job == 0) { /* job = 0 , solve a * x = b */ /* first solve l*y = b */ if (nm1 >= 1) for (k = 0; k < nm1; k++) { l = ipvt[k]; t = b[l]; if (l != k) { b[l] = b[k]; b[k] = t; } daxpy_ur(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); } /* now solve u*x = y */ for (kb = 0; kb < n; kb++) { k = n - (kb + 1); b[k] = b[k]/a[lda*k+k]; t = -b[k]; daxpy_ur(k,t,&a[lda*k+0],1,&b[0],1); } } else { /* job = nonzero, solve trans(a) * x = b */ /* first solve trans(u)*y = b */ for (k = 0; k < n; k++) { t = ddot_ur(k,&a[lda*k+0],1,&b[0],1); b[k] = (b[k] - t)/a[lda*k+k]; } /* now solve trans(l)*x = y */ if (nm1 >= 1) for (kb = 1; kb < nm1; kb++) { k = n - (kb+1); b[k] = b[k] + ddot_ur(n-(k+1),&a[lda*k+k+1],1,&b[k+1],1); l = ipvt[k]; if (l != k) { t = b[l]; b[l] = b[k]; b[k] = t; } } } } } /* ** Constant times a vector plus a vector. ** Jack Dongarra, linpack, 3/11/78. ** ROLLED version */ static void daxpy_r(int n,REAL da,REAL *dx,int incx,REAL *dy,int incy) { int i,ix,iy; if (n <= 0) return; if (da == ZERO) return; if (incx != 1 || incy != 1) { /* code for unequal increments or equal increments != 1 */ ix = 1; iy = 1; if(incx < 0) ix = (-n+1)*incx + 1; if(incy < 0)iy = (-n+1)*incy + 1; for (i = 0;i < n; i++) { dy[iy] = dy[iy] + da*dx[ix]; ix = ix + incx; iy = iy + incy; } return; } /* code for both increments equal to 1 */ for (i = 0;i < n; i++) dy[i] = dy[i] + da*dx[i]; } /* ** Forms the dot product of two vectors. ** Jack Dongarra, linpack, 3/11/78. ** ROLLED version */ static REAL ddot_r(int n,REAL *dx,int incx,REAL *dy,int incy) diff --git a/library/generate/stylesheets/cblas_plugin.c.xsl b/library/generate/stylesheets/cblas_plugin.c.xsl index f71173f..f1978e0 100644 --- a/library/generate/stylesheets/cblas_plugin.c.xsl +++ b/library/generate/stylesheets/cblas_plugin.c.xsl @@ -1,207 +1,212 @@ <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:func="http://exslt.org/functions" xmlns:dyn="http://exslt.org/dynamic" xmlns:helper="helper" extension-element-prefixes="func dyn helper"> <!-- import type definitions --> <xsl:import href="ctypes.xsl"/> <!-- import my user defined functions --> <xsl:import href="helper_functions.xsl"/> <xsl:param name="PREFIX">liftracc_plugin_</xsl:param> <xsl:param name="UUID">f4a17438-80ed-4f9f-90f1-1728df8ea630</xsl:param> <xsl:param name="PRIO">1</xsl:param> <xsl:param name="NAME">liftracc_cblas_plugin</xsl:param> <xsl:param name="DESC">wrapper to standard blas library</xsl:param> <!-- document output options --> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="*"> <xsl:apply-templates/> </xsl:template> <xsl:template match="/blas_functions"> <![CDATA[/** * \file cblas_plugin.c * \brief [generated file] */ /* This file is generated automatically, do not edit manually! */ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <stdlib.h> #include "cblas_autogen.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" #include "liftracc_selector.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = { }; #endif /* _LIFTRACC_PROFILING_ */ decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = { }; void *liftracc_plugin_fptr[CBLAS_FUNCTIONS_COUNT] = { }; plugin_info_t liftracc_plugin_info = { .uuid = "]]><xsl:value-of select="$UUID"/><![CDATA[", .name = "]]><xsl:value-of select="$NAME"/><![CDATA[", .desc = "]]><xsl:value-of select="$DESC"/><![CDATA[", .prio = ]]><xsl:value-of select="$PRIO"/><![CDATA[ }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ char *libname = getenv("USE_CBLAS_LIB"); if (libname) handle = dlopen(libname, RTLD_LAZY); if (!handle) - handle = dlopen("libcblas.so", RTLD_LAZY); + handle = dlopen("libcblas_inner.so", RTLD_LAZY); if (!handle) ERROR("%s", dlerror()); else INFO("%s loaded.", liftracc_plugin_info.name); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); int i; for (i=0; i<CBLAS_FUNCTIONS_COUNT; i++) { liftracc_plugin_fptr[i] = dlsym(handle, liftracc_cblas_function_names[i]); } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (handle) dlclose(handle); handle = 0; #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } #if _LIFTRACC_PROFILING_ == 1 int liftracc_plugin_calltest_dynamic(int a, int b, int c) { liftracc_function_timing_stop(&(liftracc_profiling_data[CALL_DYNAMIC])); /* INFO("liftracc_plugin_calltest_dynamic"); */ return rand()-a*b+c; } #endif /* _LIFTRACC_PROFILING_ */ ]]> <xsl:apply-templates/> </xsl:template> <xsl:template match="/blas_functions//*//function"> <xsl:value-of select="dyn:evaluate(concat('$',@type))"/><xsl:text> </xsl:text><xsl:value-of select="concat($PREFIX, @name, '(')"/><xsl:value-of select="helper:type-param-str()"/><![CDATA[) { INFO("%s]]><xsl:value-of select="concat('_', @name)"/><![CDATA[", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; ]]><xsl:value-of select="dyn:evaluate(concat('$',@type))"/><![CDATA[ (*func)(); ]]><xsl:if test="@type!='VOID_TYPE'"><xsl:value-of select="dyn:evaluate(concat('$',@type))"/><![CDATA[ ret = 0.0; ]]></xsl:if><![CDATA[ *(void **) (&func) = liftracc_plugin_fptr[]]><xsl:value-of select="concat('CBLAS_FUNCTION_', helper:upper-case(@name))"/><![CDATA[]; if (func != 0) { ]]><xsl:if test="@type!='VOID_TYPE'"><![CDATA[ret = ]]></xsl:if><![CDATA[(*func)(]]><xsl:value-of select="helper:param-str()"/><![CDATA[);]]><![CDATA[ + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[])); -#endif /* _LIFTRACC_PROFILING_ */]]><xsl:if test="@type!='VOID_TYPE'"><![CDATA[ - - return ret;]]></xsl:if><![CDATA[ +#endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ ]]><xsl:choose> <xsl:when test="@name='srotg'"><![CDATA[ int n = 0;]]></xsl:when> <xsl:when test="@name='srotmg'"><![CDATA[ int n = 0;]]></xsl:when> <xsl:when test="@name='drotg'"><![CDATA[ int n = 0;]]></xsl:when> <xsl:when test="@name='drotmg'"><![CDATA[ int n = 0;]]></xsl:when> <xsl:when test="@name='xerbla'"><![CDATA[ int n = 0;]]></xsl:when> <xsl:otherwise><![CDATA[]]></xsl:otherwise> </xsl:choose><![CDATA[ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[, SELECT_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[, SELECT_]]><xsl:value-of select="helper:upper-case(@name)"/><![CDATA[); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ -}]]> +]]><xsl:if test="@type!='VOID_TYPE'"><![CDATA[ + + return ret; + +]]></xsl:if><![CDATA[}]]> <xsl:text> </xsl:text> </xsl:template> </xsl:stylesheet> diff --git a/library/src/liftracc_plugin.h b/library/src/liftracc_plugin.h index 19b69cd..7b76ab2 100644 --- a/library/src/liftracc_plugin.h +++ b/library/src/liftracc_plugin.h @@ -1,80 +1,83 @@ /** * \file liftracc_plugin.h * \brief Definitions needed by the plugins * * \author Manuel Niekamp <niekma@upb.de> * \version 0.1 * \date 10/2009-03/2010 * * This File defines things related to the plugins. * Mainly this is the plugin info structur. */ #ifndef __LIFTRACC_PLUGIN_H__ #define __LIFTRACC_PLUGIN_H__ #include "liftracc_selector.h" #include "liftracc_logging.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" #endif /** * \brief Plugin information structur * This struct contains all the info to describe a * plugin in detail. */ typedef const struct { char *uuid; /**< unique id generated for example by uuidgen */ char *name; /**< short name to identify the plugin */ char *desc; /**< long description with additional info */ unsigned char prio; /**< plugin priority 0:reserved! 1-255:from low to high */ } plugin_info_t; /** * \brief Calculate the index in array. * * Inline assembler function to calculate the index in LUT. * As numbers to the power of two are used, this can be done * with the bsr instruction. * * \param probsize * Get the index to this number * \param max * To not jump behind the bounds of the array, the maximum * index return is max. * * \return * The index to use in LUT array */ static __inline__ unsigned int get_inx(unsigned int probsize, unsigned int max) { unsigned int ret = 0; __asm__ __volatile__ ( /* "Op-code src dst" AT&T syntax !!! */ "bsr %1, %0;" /* get left most 1 in bit field */ "cmp %2, %0;" /* compare to max (%0-%2) */ "jb 0f;" /* jump if below ((%0-%2)<0) */ "mov %2, %0;" /* else set output to max */ "0:" : "+r" (ret) /* outputs */ : "r" (probsize), "r" (max) /* inputs */ ); return (unsigned int) ret; } #ifdef _LIFTRACC_AUTOMODE_TRAINING_ -void set_decision_data(decision_data_t *data, +void set_decision_data(int success, + decision_data_t *data, profiling_data_t *func_data, int value, int func_id, int select_id) { decision_data_t new_value = func_data[func_id].last_time; decision_data_t old_value = data[select_id*ARRAY_SIZE+get_inx(value, ARRAY_SIZE)]; + if (old_value == 0) old_value = new_value; data[select_id*ARRAY_SIZE+get_inx(value, ARRAY_SIZE)] = (new_value+old_value)/2; - ERROR("set_decision_data(%d, %d, %d) = %llu+%llu/2", value, func_id, select_id, new_value, old_value); + if (!success || new_value == 0) data[select_id*ARRAY_SIZE+get_inx(value, ARRAY_SIZE)] = 0 - 1; + ERROR("set_decision_data(%d, %d, %d) = (%llu+%llu)/2", value, func_id, select_id, new_value, old_value); } #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ #endif // __LIFTRACC_PLUGIN_H__ diff --git a/library/src/plugins/atlas_plugin.c b/library/src/plugins/atlas_plugin.c index 3bb1f3c..0bd7aa3 100644 --- a/library/src/plugins/atlas_plugin.c +++ b/library/src/plugins/atlas_plugin.c @@ -1,268 +1,279 @@ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "atlas_aux.h" #include "atlas_level1.h" #include "atlas_level2.h" #include "atlas_level3.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = {}; #endif decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = {}; typedef enum { ATLAS_DAXPY_ID, ATLAS_DDOT_ID, ATLAS_DGEMM_ID, ATLAS_DSCAL_ID, ATLAS_IDAMAX_ID, ATLAS_FUNCTIONS_COUNT } liftracc_atlas_functions_t; const char *liftracc_atlas_function_names[] = { "ATL_daxpy", "ATL_ddot", "ATL_dgemm", "ATL_dscal", "ATL_idamax", "size_entry" }; void *liftracc_plugin_fptr[ATLAS_FUNCTIONS_COUNT] = { }; plugin_info_t liftracc_plugin_info = { .uuid = "95cd6e1c-9f7e-4628-a265-5f9e1fab6abd", .name = "liftracc_atlas_plugin", .desc = "wrapper to atlas blas library", .prio = 10 }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ char *libname = getenv("USE_ATLAS_LIB"); if (libname) handle = dlopen(libname, RTLD_LAZY); if (!handle) handle = dlopen("libatlas.so", RTLD_LAZY); if (!handle) ERROR("%s", dlerror()); else INFO("%s loaded.", liftracc_plugin_info.name); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); int i; for (i=0; i<ATLAS_FUNCTIONS_COUNT; i++) { liftracc_plugin_fptr[i] = dlsym(handle, liftracc_atlas_function_names[i]); } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (handle) dlclose(handle); handle = 0; #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } /* START OF BLAS FUNCTION IMPLEMENTATION */ void liftracc_plugin_daxpy(const int n, const double alpha, const double * x, const int incx, double * y, const int incy) { INFO("%s_daxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; void (*func)(); - *(void **) (&func) = liftracc_plugin_fptr[ATLAS_DAXPY_ID]; - if ((error = dlerror()) == 0) { + if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #if _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DAXPY, SELECT_DAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } double liftracc_plugin_ddot(const int n, const double *x, const int incx, const double *y, const int incy) { INFO("%s_ddot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double (*func)(); + double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[ATLAS_DDOT_ID]; - if ((error = dlerror()) != 0) { - ERROR("%s", error); - return 0.0; + if (func != 0) { + ret = (*func)(n, x, incx, y, incy); + } else { + success = 0; } - double ret = (*func)(n, x, incx, y, incy); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ #if _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } void liftracc_plugin_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc) { INFO("%s_dgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ + if (order != liftracc_col_major) { ERROR("Matrix not in column-major order."); return; } + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[ATLAS_DGEMM_ID]; - if ((error = dlerror()) != 0) { - ERROR("%s", error); - return; + if (func != 0) { + (*func)(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } - (*func)(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dscal(const int n, const double alpha, double * x, const int incx) { INFO("%s_dscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; void (*func)(); - *(void **) (&func) = liftracc_plugin_fptr[ATLAS_DSCAL_ID]; - if ((error = dlerror()) == 0) { + if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } liftracc_index_t liftracc_plugin_idamax(const int n, const double * x, const int incx) { INFO("%s_idamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; + liftracc_index_t ret = 0; liftracc_index_t (*func)(); - liftracc_index_t ret = 0.0; - *(void **) (&func) = liftracc_plugin_fptr[ATLAS_IDAMAX_ID]; - if ((error = dlerror()) == 0) { + if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } diff --git a/library/src/plugins/cblas_plugin.c b/library/src/plugins/cblas_plugin.c index 0a943e5..57444ca 100644 --- a/library/src/plugins/cblas_plugin.c +++ b/library/src/plugins/cblas_plugin.c @@ -1,3899 +1,4360 @@ /** * \file cblas_plugin.c * \brief [generated file] */ /* This file is generated automatically, do not edit manually! */ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <stdlib.h> #include "cblas_autogen.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" #include "liftracc_selector.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = { }; #endif /* _LIFTRACC_PROFILING_ */ decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = { }; void *liftracc_plugin_fptr[CBLAS_FUNCTIONS_COUNT] = { }; plugin_info_t liftracc_plugin_info = { .uuid = "f4a17438-80ed-4f9f-90f1-1728df8ea630", .name = "liftracc_cblas_plugin", .desc = "wrapper to standard blas library", .prio = 1 }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ char *libname = getenv("USE_CBLAS_LIB"); if (libname) handle = dlopen(libname, RTLD_LAZY); if (!handle) - handle = dlopen("libcblas.so", RTLD_LAZY); + handle = dlopen("libcblas_inner.so", RTLD_LAZY); if (!handle) ERROR("%s", dlerror()); else INFO("%s loaded.", liftracc_plugin_info.name); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); int i; for (i=0; i<CBLAS_FUNCTIONS_COUNT; i++) { liftracc_plugin_fptr[i] = dlsym(handle, liftracc_cblas_function_names[i]); } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (handle) dlclose(handle); handle = 0; #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } #if _LIFTRACC_PROFILING_ == 1 int liftracc_plugin_calltest_dynamic(int a, int b, int c) { liftracc_function_timing_stop(&(liftracc_profiling_data[CALL_DYNAMIC])); /* INFO("liftracc_plugin_calltest_dynamic"); */ return rand()-a*b+c; } #endif /* _LIFTRACC_PROFILING_ */ float liftracc_plugin_sdsdot(const int n, const float alpha, const float * x, const int incx, const float * y, const int incy) { INFO("%s_sdsdot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SDSDOT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SDSDOT]; if (func != 0) { ret = (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SDSDOT])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SDSDOT, SELECT_SDSDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SDSDOT, SELECT_SDSDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_dsdot(const int n, const float * x, const int incx, const float * y, const int incy) { INFO("%s_dsdot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSDOT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSDOT]; if (func != 0) { ret = (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSDOT])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSDOT, SELECT_DSDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSDOT, SELECT_DSDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } float liftracc_plugin_sdot(const int n, const float * x, const int incx, const float * y, const int incy) { INFO("%s_sdot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SDOT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SDOT]; if (func != 0) { ret = (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SDOT])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SDOT, SELECT_SDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SDOT, SELECT_SDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_ddot(const int n, const double * x, const int incx, const double * y, const int incy) { INFO("%s_ddot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DDOT]; if (func != 0) { ret = (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } void liftracc_plugin_cdotu_sub(const int n, const void * x, const int incx, const void * y, const int incy, void * dotu) { INFO("%s_cdotu_sub", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CDOTU_SUB])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CDOTU_SUB]; if (func != 0) { (*func)(n, x, incx, y, incy, dotu); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CDOTU_SUB])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CDOTU_SUB, SELECT_CDOTU_SUB); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CDOTU_SUB, SELECT_CDOTU_SUB); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cdotc_sub(const int n, const void * x, const int incx, const void * y, const int incy, void * dotc) { INFO("%s_cdotc_sub", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CDOTC_SUB])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CDOTC_SUB]; if (func != 0) { (*func)(n, x, incx, y, incy, dotc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CDOTC_SUB])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CDOTC_SUB, SELECT_CDOTC_SUB); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CDOTC_SUB, SELECT_CDOTC_SUB); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zdotu_sub(const int n, const void * x, const int incx, const void * y, const int incy, void * dotu) { INFO("%s_zdotu_sub", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZDOTU_SUB])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZDOTU_SUB]; if (func != 0) { (*func)(n, x, incx, y, incy, dotu); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZDOTU_SUB])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDOTU_SUB, SELECT_ZDOTU_SUB); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDOTU_SUB, SELECT_ZDOTU_SUB); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zdotc_sub(const int n, const void * x, const int incx, const void * y, const int incy, void * dotc) { INFO("%s_zdotc_sub", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZDOTC_SUB])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZDOTC_SUB]; if (func != 0) { (*func)(n, x, incx, y, incy, dotc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZDOTC_SUB])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDOTC_SUB, SELECT_ZDOTC_SUB); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDOTC_SUB, SELECT_ZDOTC_SUB); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } float liftracc_plugin_snrm2(const int n, const float * x, const int incx) { INFO("%s_snrm2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SNRM2]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SNRM2, SELECT_SNRM2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SNRM2, SELECT_SNRM2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } float liftracc_plugin_sasum(const int n, const float * x, const int incx) { INFO("%s_sasum", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SASUM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SASUM]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SASUM])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SASUM, SELECT_SASUM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SASUM, SELECT_SASUM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_dnrm2(const int n, const double * x, const int incx) { INFO("%s_dnrm2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DNRM2]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DNRM2, SELECT_DNRM2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DNRM2, SELECT_DNRM2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_dasum(const int n, const double * x, const int incx) { INFO("%s_dasum", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DASUM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DASUM]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DASUM])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DASUM, SELECT_DASUM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DASUM, SELECT_DASUM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } float liftracc_plugin_scnrm2(const int n, const void * x, const int incx) { INFO("%s_scnrm2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SCNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SCNRM2]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SCNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCNRM2, SELECT_SCNRM2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCNRM2, SELECT_SCNRM2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } float liftracc_plugin_scasum(const int n, const void * x, const int incx) { INFO("%s_scasum", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SCASUM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; float (*func)(); float ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SCASUM]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SCASUM])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCASUM, SELECT_SCASUM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCASUM, SELECT_SCASUM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_dznrm2(const int n, const void * x, const int incx) { INFO("%s_dznrm2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DZNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DZNRM2]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DZNRM2])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DZNRM2, SELECT_DZNRM2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DZNRM2, SELECT_DZNRM2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } double liftracc_plugin_dzasum(const int n, const void * x, const int incx) { INFO("%s_dzasum", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DZASUM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; double (*func)(); double ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DZASUM]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DZASUM])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DZASUM, SELECT_DZASUM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DZASUM, SELECT_DZASUM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } liftracc_index_t liftracc_plugin_isamax(const int n, const float * x, const int incx) { INFO("%s_isamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ISAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; liftracc_index_t (*func)(); liftracc_index_t ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ISAMAX]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ISAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ISAMAX, SELECT_ISAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ISAMAX, SELECT_ISAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } liftracc_index_t liftracc_plugin_idamax(const int n, const double * x, const int incx) { INFO("%s_idamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; liftracc_index_t (*func)(); liftracc_index_t ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_IDAMAX]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } liftracc_index_t liftracc_plugin_icamax(const int n, const void * x, const int incx) { INFO("%s_icamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ICAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; liftracc_index_t (*func)(); liftracc_index_t ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ICAMAX]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ICAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ICAMAX, SELECT_ICAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ICAMAX, SELECT_ICAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } liftracc_index_t liftracc_plugin_izamax(const int n, const void * x, const int incx) { INFO("%s_izamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_IZAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; liftracc_index_t (*func)(); liftracc_index_t ret = 0.0; *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_IZAMAX]; if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_IZAMAX])); #endif /* _LIFTRACC_PROFILING_ */ - return ret; - #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IZAMAX, SELECT_IZAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IZAMAX, SELECT_IZAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ + + + return ret; + } void liftracc_plugin_sswap(const int n, float * x, const int incx, float * y, const int incy) { INFO("%s_sswap", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSWAP])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSWAP]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSWAP])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSWAP, SELECT_SSWAP); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSWAP, SELECT_SSWAP); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_scopy(const int n, const float * x, const int incx, float * y, const int incy) { INFO("%s_scopy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SCOPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SCOPY]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SCOPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCOPY, SELECT_SCOPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SCOPY, SELECT_SCOPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_saxpy(const int n, const float alpha, const float * x, const int incx, float * y, const int incy) { INFO("%s_saxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SAXPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SAXPY]; if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SAXPY, SELECT_SAXPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SAXPY, SELECT_SAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dswap(const int n, double * x, const int incx, double * y, const int incy) { INFO("%s_dswap", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSWAP])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSWAP]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSWAP])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSWAP, SELECT_DSWAP); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSWAP, SELECT_DSWAP); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dcopy(const int n, const double * x, const int incx, double * y, const int incy) { INFO("%s_dcopy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DCOPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DCOPY]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DCOPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DCOPY, SELECT_DCOPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DCOPY, SELECT_DCOPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_daxpy(const int n, const double alpha, const double * x, const int incx, double * y, const int incy) { INFO("%s_daxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DAXPY]; if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DAXPY, SELECT_DAXPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DAXPY, SELECT_DAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cswap(const int n, void * x, const int incx, void * y, const int incy) { INFO("%s_cswap", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSWAP])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSWAP]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSWAP])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSWAP, SELECT_CSWAP); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSWAP, SELECT_CSWAP); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ccopy(const int n, const void * x, const int incx, void * y, const int incy) { INFO("%s_ccopy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CCOPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CCOPY]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CCOPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CCOPY, SELECT_CCOPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CCOPY, SELECT_CCOPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_caxpy(const int n, const void * alpha, const void * x, const int incx, void * y, const int incy) { INFO("%s_caxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CAXPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CAXPY]; if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CAXPY, SELECT_CAXPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CAXPY, SELECT_CAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zswap(const int n, void * x, const int incx, void * y, const int incy) { INFO("%s_zswap", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZSWAP])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZSWAP]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZSWAP])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSWAP, SELECT_ZSWAP); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSWAP, SELECT_ZSWAP); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zcopy(const int n, const void * x, const int incx, void * y, const int incy) { INFO("%s_zcopy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZCOPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZCOPY]; if (func != 0) { (*func)(n, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZCOPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZCOPY, SELECT_ZCOPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZCOPY, SELECT_ZCOPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zaxpy(const int n, const void * alpha, const void * x, const int incx, void * y, const int incy) { INFO("%s_zaxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZAXPY])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZAXPY]; if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZAXPY, SELECT_ZAXPY); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZAXPY, SELECT_ZAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_srotg(float * a, float * b, float * c, float * s) { INFO("%s_srotg", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SROTG])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SROTG]; if (func != 0) { (*func)(a, b, c, s); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SROTG])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ int n = 0; - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTG, SELECT_SROTG); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTG, SELECT_SROTG); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_srotmg(float * d1, float * d2, float * b1, const float b2, float * p) { INFO("%s_srotmg", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SROTMG])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SROTMG]; if (func != 0) { (*func)(d1, d2, b1, b2, p); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SROTMG])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ int n = 0; - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTMG, SELECT_SROTMG); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTMG, SELECT_SROTMG); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_srot(const int n, float * x, const int incx, float * y, const int incy, const float c, const float s) { INFO("%s_srot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SROT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SROT]; if (func != 0) { (*func)(n, x, incx, y, incy, c, s); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SROT])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROT, SELECT_SROT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROT, SELECT_SROT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_srotm(const int n, float * x, const int incx, float * y, const int incy, const float * p) { INFO("%s_srotm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SROTM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SROTM]; if (func != 0) { (*func)(n, x, incx, y, incy, p); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SROTM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTM, SELECT_SROTM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SROTM, SELECT_SROTM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_drotg(double * a, double * b, double * c, double * s) { INFO("%s_drotg", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DROTG])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DROTG]; if (func != 0) { (*func)(a, b, c, s); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DROTG])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ int n = 0; - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTG, SELECT_DROTG); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTG, SELECT_DROTG); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_drotmg(double * d1, double * d2, double * b1, const double b2, double * p) { INFO("%s_drotmg", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DROTMG])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DROTMG]; if (func != 0) { (*func)(d1, d2, b1, b2, p); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DROTMG])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ int n = 0; - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTMG, SELECT_DROTMG); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTMG, SELECT_DROTMG); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_drot(const int n, double * x, const int incx, double * y, const int incy, const double c, const double s) { INFO("%s_drot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DROT])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DROT]; if (func != 0) { (*func)(n, x, incx, y, incy, c, s); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DROT])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROT, SELECT_DROT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROT, SELECT_DROT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_drotm(const int n, double * x, const int incx, double * y, const int incy, const double * p) { INFO("%s_drotm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DROTM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DROTM]; if (func != 0) { (*func)(n, x, incx, y, incy, p); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DROTM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTM, SELECT_DROTM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DROTM, SELECT_DROTM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sscal(const int n, const float alpha, float * x, const int incx) { INFO("%s_sscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSCAL, SELECT_SSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSCAL, SELECT_SSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dscal(const int n, const double alpha, double * x, const int incx) { INFO("%s_dscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cscal(const int n, const void * alpha, void * x, const int incx) { INFO("%s_cscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSCAL, SELECT_CSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSCAL, SELECT_CSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zscal(const int n, const void * alpha, void * x, const int incx) { INFO("%s_zscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSCAL, SELECT_ZSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSCAL, SELECT_ZSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_csscal(const int n, const float alpha, void * x, const int incx) { INFO("%s_csscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSSCAL, SELECT_CSSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSSCAL, SELECT_CSSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zdscal(const int n, const double alpha, void * x, const int incx) { INFO("%s_zdscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZDSCAL])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZDSCAL]; if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZDSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDSCAL, SELECT_ZDSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZDSCAL, SELECT_ZDSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sgemv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const float alpha, const float * a, const int lda, const float * x, const int incx, const float beta, float * y, const int incy) { INFO("%s_sgemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SGEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SGEMV]; if (func != 0) { (*func)(order, transa, m, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SGEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGEMV, SELECT_SGEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGEMV, SELECT_SGEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sgbmv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const int kl, const int ku, const float alpha, const float * a, const int lda, const float * x, const int incx, const float beta, float * y, const int incy) { INFO("%s_sgbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SGBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SGBMV]; if (func != 0) { (*func)(order, transa, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SGBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGBMV, SELECT_SGBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGBMV, SELECT_SGBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_strmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const float * a, const int lda, float * x, const int incx) { INFO("%s_strmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STRMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STRMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STRMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRMV, SELECT_STRMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRMV, SELECT_STRMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_stbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const float * a, const int lda, float * x, const int incx) { INFO("%s_stbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STBMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STBMV, SELECT_STBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STBMV, SELECT_STBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_stpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const float * ap, float * x, const int incx) { INFO("%s_stpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STPMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STPMV, SELECT_STPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STPMV, SELECT_STPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_strsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const float * a, const int lda, float * x, const int incx) { INFO("%s_strsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STRSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STRSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STRSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRSV, SELECT_STRSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRSV, SELECT_STRSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_stbsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const float * a, const int lda, float * x, const int incx) { INFO("%s_stbsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STBSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STBSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STBSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STBSV, SELECT_STBSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STBSV, SELECT_STBSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_stpsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const float * ap, float * x, const int incx) { INFO("%s_stpsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STPSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STPSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STPSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STPSV, SELECT_STPSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STPSV, SELECT_STPSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dgemv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const double alpha, const double * a, const int lda, const double * x, const int incx, const double beta, double * y, const int incy) { INFO("%s_dgemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DGEMV]; if (func != 0) { (*func)(order, transa, m, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMV, SELECT_DGEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMV, SELECT_DGEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dgbmv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const int kl, const int ku, const double alpha, const double * a, const int lda, const double * x, const int incx, const double beta, double * y, const int incy) { INFO("%s_dgbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DGBMV]; if (func != 0) { (*func)(order, transa, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGBMV, SELECT_DGBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGBMV, SELECT_DGBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtrmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const double * a, const int lda, double * x, const int incx) { INFO("%s_dtrmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTRMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTRMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTRMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRMV, SELECT_DTRMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRMV, SELECT_DTRMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const double * a, const int lda, double * x, const int incx) { INFO("%s_dtbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTBMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTBMV, SELECT_DTBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTBMV, SELECT_DTBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const double * ap, double * x, const int incx) { INFO("%s_dtpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTPMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTPMV, SELECT_DTPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTPMV, SELECT_DTPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtrsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const double * a, const int lda, double * x, const int incx) { INFO("%s_dtrsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTRSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTRSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTRSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRSV, SELECT_DTRSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRSV, SELECT_DTRSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtbsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const double * a, const int lda, double * x, const int incx) { INFO("%s_dtbsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTBSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTBSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTBSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTBSV, SELECT_DTBSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTBSV, SELECT_DTBSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtpsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const double * ap, double * x, const int incx) { INFO("%s_dtpsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTPSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTPSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTPSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTPSV, SELECT_DTPSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTPSV, SELECT_DTPSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cgemv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_cgemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CGEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CGEMV]; if (func != 0) { (*func)(order, transa, m, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CGEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGEMV, SELECT_CGEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGEMV, SELECT_CGEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cgbmv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const int kl, const int ku, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_cgbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CGBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CGBMV]; if (func != 0) { (*func)(order, transa, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CGBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGBMV, SELECT_CGBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGBMV, SELECT_CGBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctrmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * a, const int lda, void * x, const int incx) { INFO("%s_ctrmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTRMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTRMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTRMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRMV, SELECT_CTRMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRMV, SELECT_CTRMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const void * a, const int lda, void * x, const int incx) { INFO("%s_ctbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTBMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTBMV, SELECT_CTBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTBMV, SELECT_CTBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * ap, void * x, const int incx) { INFO("%s_ctpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTPMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTPMV, SELECT_CTPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTPMV, SELECT_CTPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctrsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * a, const int lda, void * x, const int incx) { INFO("%s_ctrsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTRSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTRSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTRSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRSV, SELECT_CTRSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRSV, SELECT_CTRSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctbsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const void * a, const int lda, void * x, const int incx) { INFO("%s_ctbsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTBSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTBSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTBSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTBSV, SELECT_CTBSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTBSV, SELECT_CTBSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctpsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * ap, void * x, const int incx) { INFO("%s_ctpsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTPSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTPSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTPSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTPSV, SELECT_CTPSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTPSV, SELECT_CTPSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zgemv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_zgemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZGEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZGEMV]; if (func != 0) { (*func)(order, transa, m, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZGEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGEMV, SELECT_ZGEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGEMV, SELECT_ZGEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zgbmv(const liftracc_order_t order, const liftracc_transpose_t transa, const int m, const int n, const int kl, const int ku, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_zgbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZGBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZGBMV]; if (func != 0) { (*func)(order, transa, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZGBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGBMV, SELECT_ZGBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGBMV, SELECT_ZGBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztrmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * a, const int lda, void * x, const int incx) { INFO("%s_ztrmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTRMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRMV, SELECT_ZTRMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRMV, SELECT_ZTRMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const void * a, const int lda, void * x, const int incx) { INFO("%s_ztbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTBMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTBMV, SELECT_ZTBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTBMV, SELECT_ZTBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * ap, void * x, const int incx) { INFO("%s_ztpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTPMV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTPMV, SELECT_ZTPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTPMV, SELECT_ZTPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztrsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * a, const int lda, void * x, const int incx) { INFO("%s_ztrsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTRSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRSV, SELECT_ZTRSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRSV, SELECT_ZTRSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztbsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const int k, const void * a, const int lda, void * x, const int incx) { INFO("%s_ztbsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTBSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTBSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, k, a, lda, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTBSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTBSV, SELECT_ZTBSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTBSV, SELECT_ZTBSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztpsv(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int n, const void * ap, void * x, const int incx) { INFO("%s_ztpsv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTPSV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTPSV]; if (func != 0) { (*func)(order, uplo, transa, diag, n, ap, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTPSV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTPSV, SELECT_ZTPSV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTPSV, SELECT_ZTPSV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssymv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * a, const int lda, const float * x, const int incx, const float beta, float * y, const int incy) { INFO("%s_ssymv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYMV]; if (func != 0) { (*func)(order, uplo, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYMV, SELECT_SSYMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYMV, SELECT_SSYMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const int k, const float alpha, const float * a, const int lda, const float * x, const int incx, const float beta, float * y, const int incy) { INFO("%s_ssbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSBMV]; if (func != 0) { (*func)(order, uplo, n, k, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSBMV, SELECT_SSBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSBMV, SELECT_SSBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sspmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * ap, const float * x, const int incx, const float beta, float * y, const int incy) { INFO("%s_sspmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSPMV]; if (func != 0) { (*func)(order, uplo, n, alpha, ap, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPMV, SELECT_SSPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPMV, SELECT_SSPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sger(const liftracc_order_t order, const int m, const int n, const float alpha, const float * x, const int incx, const float * y, const int incy, float * a, const int lda) { INFO("%s_sger", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SGER])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SGER]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SGER])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGER, SELECT_SGER); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGER, SELECT_SGER); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssyr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * x, const int incx, float * a, const int lda) { INFO("%s_ssyr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR, SELECT_SSYR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR, SELECT_SSYR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sspr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * x, const int incx, float * ap) { INFO("%s_sspr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSPR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSPR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, ap); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSPR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPR, SELECT_SSPR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPR, SELECT_SSPR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssyr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * x, const int incx, const float * y, const int incy, float * a, const int lda) { INFO("%s_ssyr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR2, SELECT_SSYR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR2, SELECT_SSYR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sspr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const float * x, const int incx, const float * y, const int incy, float * a) { INFO("%s_sspr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSPR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSPR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSPR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPR2, SELECT_SSPR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSPR2, SELECT_SSPR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsymv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * a, const int lda, const double * x, const int incx, const double beta, double * y, const int incy) { INFO("%s_dsymv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYMV]; if (func != 0) { (*func)(order, uplo, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYMV, SELECT_DSYMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYMV, SELECT_DSYMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const int k, const double alpha, const double * a, const int lda, const double * x, const int incx, const double beta, double * y, const int incy) { INFO("%s_dsbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSBMV]; if (func != 0) { (*func)(order, uplo, n, k, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSBMV, SELECT_DSBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSBMV, SELECT_DSBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dspmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * ap, const double * x, const int incx, const double beta, double * y, const int incy) { INFO("%s_dspmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSPMV]; if (func != 0) { (*func)(order, uplo, n, alpha, ap, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPMV, SELECT_DSPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPMV, SELECT_DSPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dger(const liftracc_order_t order, const int m, const int n, const double alpha, const double * x, const int incx, const double * y, const int incy, double * a, const int lda) { INFO("%s_dger", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGER])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DGER]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGER])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGER, SELECT_DGER); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGER, SELECT_DGER); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsyr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * x, const int incx, double * a, const int lda) { INFO("%s_dsyr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR, SELECT_DSYR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR, SELECT_DSYR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dspr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * x, const int incx, double * ap) { INFO("%s_dspr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSPR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSPR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, ap); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSPR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPR, SELECT_DSPR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPR, SELECT_DSPR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsyr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * x, const int incx, const double * y, const int incy, double * a, const int lda) { INFO("%s_dsyr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR2, SELECT_DSYR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR2, SELECT_DSYR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dspr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const double * x, const int incx, const double * y, const int incy, double * a) { INFO("%s_dspr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSPR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSPR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSPR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPR2, SELECT_DSPR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSPR2, SELECT_DSPR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chemv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_chemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHEMV]; if (func != 0) { (*func)(order, uplo, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHEMV, SELECT_CHEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHEMV, SELECT_CHEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const int k, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_chbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHBMV]; if (func != 0) { (*func)(order, uplo, n, k, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHBMV, SELECT_CHBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHBMV, SELECT_CHBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * ap, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_chpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHPMV]; if (func != 0) { (*func)(order, uplo, n, alpha, ap, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPMV, SELECT_CHPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPMV, SELECT_CHPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cgeru(const liftracc_order_t order, const int m, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_cgeru", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CGERU])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CGERU]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CGERU])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGERU, SELECT_CGERU); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGERU, SELECT_CGERU); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cgerc(const liftracc_order_t order, const int m, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_cgerc", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CGERC])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CGERC]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CGERC])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGERC, SELECT_CGERC); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGERC, SELECT_CGERC); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cher(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const void * x, const int incx, void * a, const int lda) { INFO("%s_cher", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHER])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHER]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHER])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER, SELECT_CHER); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER, SELECT_CHER); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chpr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const float alpha, const void * x, const int incx, void * a) { INFO("%s_chpr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHPR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHPR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHPR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPR, SELECT_CHPR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPR, SELECT_CHPR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cher2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_cher2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHER2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHER2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHER2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER2, SELECT_CHER2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER2, SELECT_CHER2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chpr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * ap) { INFO("%s_chpr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHPR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHPR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, ap); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHPR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPR2, SELECT_CHPR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHPR2, SELECT_CHPR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhemv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_zhemv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHEMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHEMV]; if (func != 0) { (*func)(order, uplo, n, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHEMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHEMV, SELECT_ZHEMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHEMV, SELECT_ZHEMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhbmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const int k, const void * alpha, const void * a, const int lda, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_zhbmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHBMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHBMV]; if (func != 0) { (*func)(order, uplo, n, k, alpha, a, lda, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHBMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHBMV, SELECT_ZHBMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHBMV, SELECT_ZHBMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhpmv(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * ap, const void * x, const int incx, const void * beta, void * y, const int incy) { INFO("%s_zhpmv", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPMV])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHPMV]; if (func != 0) { (*func)(order, uplo, n, alpha, ap, x, incx, beta, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPMV])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPMV, SELECT_ZHPMV); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPMV, SELECT_ZHPMV); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zgeru(const liftracc_order_t order, const int m, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_zgeru", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZGERU])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZGERU]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZGERU])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGERU, SELECT_ZGERU); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGERU, SELECT_ZGERU); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zgerc(const liftracc_order_t order, const int m, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_zgerc", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZGERC])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZGERC]; if (func != 0) { (*func)(order, m, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZGERC])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGERC, SELECT_ZGERC); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGERC, SELECT_ZGERC); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zher(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const void * x, const int incx, void * a, const int lda) { INFO("%s_zher", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHER]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER, SELECT_ZHER); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER, SELECT_ZHER); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhpr(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const double alpha, const void * x, const int incx, void * a) { INFO("%s_zhpr", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPR])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHPR]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, a); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPR])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPR, SELECT_ZHPR); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPR, SELECT_ZHPR); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zher2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * a, const int lda) { INFO("%s_zher2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHER2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, a, lda); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER2, SELECT_ZHER2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER2, SELECT_ZHER2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhpr2(const liftracc_order_t order, const liftracc_uplo_t uplo, const int n, const void * alpha, const void * x, const int incx, const void * y, const int incy, void * ap) { INFO("%s_zhpr2", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPR2])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHPR2]; if (func != 0) { (*func)(order, uplo, n, alpha, x, incx, y, incy, ap); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHPR2])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPR2, SELECT_ZHPR2); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHPR2, SELECT_ZHPR2); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_sgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const float alpha, const float * a, const int lda, const float * b, const int ldb, const float beta, float * c, const int ldc) { INFO("%s_sgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SGEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SGEMM]; if (func != 0) { (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGEMM, SELECT_SGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SGEMM, SELECT_SGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssymm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const float alpha, const float * a, const int lda, const float * b, const int ldb, const float beta, float * c, const int ldc) { INFO("%s_ssymm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYMM, SELECT_SSYMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYMM, SELECT_SSYMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssyrk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const float alpha, const float * a, const int lda, const float beta, float * c, const int ldc) { INFO("%s_ssyrk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYRK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYRK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYRK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYRK, SELECT_SSYRK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYRK, SELECT_SSYRK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ssyr2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const float alpha, const float * a, const int lda, const float * b, const int ldb, const float beta, float * c, const int ldc) { INFO("%s_ssyr2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_SSYR2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_SSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR2K, SELECT_SSYR2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_SSYR2K, SELECT_SSYR2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_strmm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const float alpha, const float * a, const int lda, float * b, const int ldb) { INFO("%s_strmm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STRMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STRMM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STRMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRMM, SELECT_STRMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRMM, SELECT_STRMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_strsm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const float alpha, const float * a, const int lda, float * b, const int ldb) { INFO("%s_strsm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_STRSM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_STRSM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_STRSM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRSM, SELECT_STRSM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_STRSM, SELECT_STRSM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double * a, const int lda, const double * b, const int ldb, const double beta, double * c, const int ldc) { INFO("%s_dgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DGEMM]; if (func != 0) { (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsymm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const double alpha, const double * a, const int lda, const double * b, const int ldb, const double beta, double * c, const int ldc) { INFO("%s_dsymm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYMM, SELECT_DSYMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYMM, SELECT_DSYMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsyrk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const double alpha, const double * a, const int lda, const double beta, double * c, const int ldc) { INFO("%s_dsyrk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYRK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYRK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYRK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYRK, SELECT_DSYRK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYRK, SELECT_DSYRK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dsyr2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const double alpha, const double * a, const int lda, const double * b, const int ldb, const double beta, double * c, const int ldc) { INFO("%s_dsyr2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DSYR2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR2K, SELECT_DSYR2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSYR2K, SELECT_DSYR2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtrmm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const double alpha, const double * a, const int lda, double * b, const int ldb) { INFO("%s_dtrmm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTRMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTRMM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTRMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRMM, SELECT_DTRMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRMM, SELECT_DTRMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dtrsm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const double alpha, const double * a, const int lda, double * b, const int ldb) { INFO("%s_dtrsm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DTRSM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_DTRSM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DTRSM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRSM, SELECT_DTRSM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DTRSM, SELECT_DTRSM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_cgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CGEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CGEMM]; if (func != 0) { (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGEMM, SELECT_CGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CGEMM, SELECT_CGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_csymm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_csymm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSYMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSYMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSYMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYMM, SELECT_CSYMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYMM, SELECT_CSYMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_csyrk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * beta, void * c, const int ldc) { INFO("%s_csyrk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSYRK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSYRK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSYRK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYRK, SELECT_CSYRK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYRK, SELECT_CSYRK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_csyr2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_csyr2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CSYR2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYR2K, SELECT_CSYR2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CSYR2K, SELECT_CSYR2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctrmm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const void * alpha, const void * a, const int lda, void * b, const int ldb) { INFO("%s_ctrmm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTRMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTRMM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTRMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRMM, SELECT_CTRMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRMM, SELECT_CTRMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ctrsm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const void * alpha, const void * a, const int lda, void * b, const int ldb) { INFO("%s_ctrsm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CTRSM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CTRSM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CTRSM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRSM, SELECT_CTRSM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CTRSM, SELECT_CTRSM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_zgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZGEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZGEMM]; if (func != 0) { (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGEMM, SELECT_ZGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZGEMM, SELECT_ZGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zsymm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_zsymm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZSYMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYMM, SELECT_ZSYMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYMM, SELECT_ZSYMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zsyrk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * beta, void * c, const int ldc) { INFO("%s_zsyrk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYRK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZSYRK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYRK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYRK, SELECT_ZSYRK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYRK, SELECT_ZSYRK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zsyr2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_zsyr2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZSYR2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZSYR2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYR2K, SELECT_ZSYR2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZSYR2K, SELECT_ZSYR2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztrmm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const void * alpha, const void * a, const int lda, void * b, const int ldb) { INFO("%s_ztrmm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTRMM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRMM, SELECT_ZTRMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRMM, SELECT_ZTRMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_ztrsm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const liftracc_transpose_t transa, const liftracc_diag_t diag, const int m, const int n, const void * alpha, const void * a, const int lda, void * b, const int ldb) { INFO("%s_ztrsm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRSM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZTRSM]; if (func != 0) { (*func)(order, side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZTRSM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRSM, SELECT_ZTRSM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZTRSM, SELECT_ZTRSM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_chemm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_chemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHEMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHEMM, SELECT_CHEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHEMM, SELECT_CHEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cherk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const float alpha, const void * a, const int lda, const float beta, void * c, const int ldc) { INFO("%s_cherk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHERK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHERK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHERK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHERK, SELECT_CHERK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHERK, SELECT_CHERK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_cher2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const float beta, void * c, const int ldc) { INFO("%s_cher2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_CHER2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_CHER2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_CHER2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER2K, SELECT_CHER2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_CHER2K, SELECT_CHER2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zhemm(const liftracc_order_t order, const liftracc_side_t side, const liftracc_uplo_t uplo, const int m, const int n, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const void * beta, void * c, const int ldc) { INFO("%s_zhemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHEMM])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHEMM]; if (func != 0) { (*func)(order, side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHEMM, SELECT_ZHEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHEMM, SELECT_ZHEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zherk(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const double alpha, const void * a, const int lda, const double beta, void * c, const int ldc) { INFO("%s_zherk", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHERK])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHERK]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHERK])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHERK, SELECT_ZHERK); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHERK, SELECT_ZHERK); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_zher2k(const liftracc_order_t order, const liftracc_uplo_t uplo, const liftracc_transpose_t trans, const int n, const int k, const void * alpha, const void * a, const int lda, const void * b, const int ldb, const double beta, void * c, const int ldc) { INFO("%s_zher2k", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER2K])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_ZHER2K]; if (func != 0) { (*func)(order, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_ZHER2K])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER2K, SELECT_ZHER2K); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_ZHER2K, SELECT_ZHER2K); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_xerbla(int p, const char * rout, const char * form) { INFO("%s_xerbla", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_XERBLA])); #endif /* _LIFTRACC_PROFILING_ */ - + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CBLAS_FUNCTION_XERBLA]; if (func != 0) { (*func)(p, rout, form); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_XERBLA])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ int n = 0; - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_XERBLA, SELECT_XERBLA); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_XERBLA, SELECT_XERBLA); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } diff --git a/library/src/plugins/clearspeed_plugin.c b/library/src/plugins/clearspeed_plugin.c index 769e359..f8b2b5d 100644 --- a/library/src/plugins/clearspeed_plugin.c +++ b/library/src/plugins/clearspeed_plugin.c @@ -1,175 +1,177 @@ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = {}; #endif decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = {}; typedef enum { CLEAR_DGEMM_ID, CLEAR_FUNCTIONS_COUNT } liftracc_clear_functions_t; const char *liftracc_clear_function_names[] = { "DGEMM", "size_entry" }; void *liftracc_plugin_fptr[CLEAR_FUNCTIONS_COUNT] = { }; plugin_info_t liftracc_plugin_info = { .uuid = "7bedd79d-62b6-4210-b221-98ebf540057a", .name = "liftracc_clearspeed_plugin", .desc = "wrapper to clearspeed blas library", .prio = 30 }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ char *libname = getenv("USE_CSXL_LIB"); if (libname) handle = dlopen(libname, RTLD_LAZY); if (!handle) handle = dlopen("libcsxl_mkl.so", RTLD_LAZY); if (!handle) ERROR("%s", dlerror()); else INFO("%s loaded.", liftracc_plugin_info.name); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); int i; for (i=0; i<CLEAR_FUNCTIONS_COUNT; i++) { liftracc_plugin_fptr[i] = dlsym(handle, liftracc_clear_function_names[i]); } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (handle) dlclose(handle); handle = 0; #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } /* START OF BLAS FUNCTION IMPLEMENTATION */ void liftracc_plugin_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc) { INFO("%s_dgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ + if (order != liftracc_col_major) { ERROR("Matrix not in column-major order."); return; } + + int success = 1; void (*func)(); *(void **) (&func) = liftracc_plugin_fptr[CLEAR_DGEMM_ID]; - if ((error = dlerror()) != 0) { - ERROR("%s", error); - return; - } - char ta, tb; switch (transa) { case liftracc_no_trans: ta = 'N'; break; case liftracc_trans: ta = 'T'; break; case liftracc_conj_trans: ta = 'C'; break; default: ta = 'N'; break; } switch (transb) { case liftracc_no_trans: tb = 'N'; break; case liftracc_trans: tb = 'T'; break; case liftracc_conj_trans: tb = 'C'; break; default: tb = 'N'; break; } - (*func)((const char *) &ta, (const char *) &tb, - &m, &n, &k, - &alpha, a, &lda, - b, &ldb, &beta, - c, &ldc); + if (func != 0) { + (*func)((const char *) &ta, (const char *) &tb, + &m, &n, &k, + &alpha, a, &lda, + b, &ldb, &beta, + c, &ldc); + } else { + success = 0; + } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } diff --git a/library/src/plugins/cublas_plugin.c b/library/src/plugins/cublas_plugin.c index 8122439..43f28a2 100644 --- a/library/src/plugins/cublas_plugin.c +++ b/library/src/plugins/cublas_plugin.c @@ -1,309 +1,338 @@ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "cublas.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = {}; #endif decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = {}; plugin_info_t liftracc_plugin_info = { .uuid = "4241c224-99c9-4c44-979f-32c6ac5fc9a4", .name = "liftracc_cublas_plugin", .desc = "wrapper to cublas library", .prio = 20 }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ if (cublasInit()==CUBLAS_STATUS_SUCCESS) INFO("%s loaded.", liftracc_plugin_info.name); else ERROR("cublasInit() failed!"); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (cublasShutdown()==CUBLAS_STATUS_SUCCESS) INFO("%s unloaded.", liftracc_plugin_info.name); else ERROR("cublasShutdown() failed!"); #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } /* START OF BLAS FUNCTION IMPLEMENTATION */ void liftracc_plugin_daxpy(const int n, const double alpha, const double * x, const int incx, double * y, const int incy) { INFO("%s_daxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double* dev_x; double* dev_y; cublasAlloc(n, sizeof(*x), (void**)&dev_x); cublasAlloc(n, sizeof(*y), (void**)&dev_y); cublasSetVector(n, sizeof(*x), x, incx, dev_x, incx); cublasSetVector(n, sizeof(*y), y, incy, dev_y, incy); cublasDaxpy(n, alpha, dev_x, incx, dev_y, incy); - if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) + if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) { + success = 0; ERROR("cublas function ERROR"); + } cublasGetVector(n, sizeof(*y), dev_y, incy, y, incy); cublasFree(dev_x); cublasFree(dev_y); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DAXPY, SELECT_DAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } double liftracc_plugin_ddot(const int n, const double *x, const int incx, const double *y, const int incy) { INFO("%s_ddot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double* dev_x; double* dev_y; + double ret = 0.0; cublasAlloc(n, sizeof(*x), (void**)&dev_x); cublasAlloc(n, sizeof(*y), (void**)&dev_y); cublasSetVector(n, sizeof(*x), x, incx, dev_x, incx); cublasSetVector(n, sizeof(*y), y, incy, dev_y, incy); - double ret = cublasDdot(n, dev_x, incx, dev_y, incy); + ret = cublasDdot(n, dev_x, incx, dev_y, incy); - if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) + if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) { + success = 0; ERROR("cublas function ERROR"); + } cublasFree(dev_x); cublasFree(dev_y); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } void liftracc_plugin_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc) { INFO("%s_dgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #if _LIFTRACC_PROFILING_ == 10 liftracc_function_timing_start(&(liftracc_profiling_data[PARAM_CONV])); #endif /* _LIFTRACC_PROFILING_ */ + if (order != liftracc_col_major) { ERROR("Matrix not in column-major order."); return; } char ta, tb; switch (transa) { case liftracc_no_trans: ta = 'N'; break; case liftracc_trans: ta = 'T'; break; case liftracc_conj_trans: ta = 'C'; break; default: ta = 'N'; break; } switch (transb) { case liftracc_no_trans: tb = 'N'; break; case liftracc_trans: tb = 'T'; break; case liftracc_conj_trans: tb = 'C'; break; default: tb = 'N'; break; } #if _LIFTRACC_PROFILING_ == 10 liftracc_function_timing_stop(&(liftracc_profiling_data[PARAM_CONV])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double* dev_a; double* dev_b; double* dev_c; - cublasAlloc(m*k, sizeof(*a), (void**)&dev_a); - cublasAlloc(k*n, sizeof(*b), (void**)&dev_b); - cublasAlloc(m*n, sizeof(*c), (void**)&dev_c); + if (cublasAlloc(m*k, sizeof(*a), (void**)&dev_a)!=CUBLAS_STATUS_SUCCESS) { + success = 0; + ERROR("cublas alloc"); + } + + if (cublasAlloc(k*n, sizeof(*b), (void**)&dev_b)!=CUBLAS_STATUS_SUCCESS) { + success = 0; + ERROR("cublas alloc"); + } + + if (cublasAlloc(m*n, sizeof(*c), (void**)&dev_c)!=CUBLAS_STATUS_SUCCESS) { + success = 0; + ERROR("cublas alloc"); + } cublasSetMatrix(m, k, sizeof(*a), a, lda, dev_a, lda); cublasSetMatrix(k, n, sizeof(*a), a, ldb, dev_b, ldb); cublasSetMatrix(m, n, sizeof(*a), a, ldc, dev_c, ldc); cublasDgemm(ta, tb, m, n, k, alpha, dev_a, lda, dev_b, ldb, beta, dev_c, ldc); - if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) - ERROR("cublas function ERROR"); + if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) { + success = 0; + ERROR("cublas function exec"); + } cublasGetMatrix(m, n, sizeof(*c), dev_c, ldc, c, ldc); cublasFree(dev_a); cublasFree(dev_b); cublasFree(dev_c); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dscal(const int n, const double alpha, double * x, const int incx) { INFO("%s_dscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double* dev_x; cublasAlloc(n, sizeof(*x), (void**)&dev_x); cublasSetVector(n, sizeof(*x), x, incx, dev_x, incx); cublasDscal(n, alpha, dev_x, incx); - if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) + if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) { + success = 0; ERROR("cublas function ERROR"); + } cublasGetVector(n, sizeof(*x), dev_x, incx, x, incx); cublasFree(dev_x); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } liftracc_index_t liftracc_plugin_idamax(const int n, const double * x, const int incx) { INFO("%s_idamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; double* dev_x; + int ret = 0; cublasAlloc(n, sizeof(*x), (void**)&dev_x); cublasSetVector(n, sizeof(*x), x, incx, dev_x, incx); - int ret = cublasIdamax(n, dev_x, incx); + ret = cublasIdamax(n, dev_x, incx); - if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) + if (cublasGetError()!=CUBLAS_STATUS_SUCCESS) { + success = 0; ERROR("cublas function ERROR"); + } cublasFree(dev_x); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } diff --git a/library/src/plugins/goto2_plugin.c b/library/src/plugins/goto2_plugin.c index f03837f..d23cf22 100644 --- a/library/src/plugins/goto2_plugin.c +++ b/library/src/plugins/goto2_plugin.c @@ -1,263 +1,272 @@ #include "liftracc.h" #include "liftracc_plugin.h" #include "liftracc_logging.h" #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "cblas.h" #if _LIFTRACC_PROFILING_ > 0 #include "liftracc_profiling.h" profiling_data_t function_profiling_data[LIFTRACC_FUNCTIONS_COUNT] = {}; #endif decision_data_t decision_data[FUNCTION_COUNT*ARRAY_SIZE] = {}; typedef enum { GOTO_DAXPY_ID, GOTO_DDOT_ID, GOTO_DGEMM_ID, GOTO_DSCAL_ID, GOTO_IDAMAX_ID, GOTO_FUNCTIONS_COUNT } liftracc_atlas_functions_t; const char *liftracc_goto_function_names[] = { "cblas_daxpy", "cblas_ddot", "cblas_dgemm", "cblas_dscal", "cblas_idamax", "size_entry" }; void *liftracc_plugin_fptr[GOTO_FUNCTIONS_COUNT] = { }; plugin_info_t liftracc_plugin_info = { .uuid = "829a1670-46b0-450e-9f85-3d6a65a9efcb", .name = "liftracc_libgoto2_plugin", .desc = "wrapper to libgoto2 blas library", .prio = 40, }; void *handle = 0; char *error = 0; void __attribute__ ((constructor)) liftracc_plugin_load(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ char *libname = getenv("USE_GOTO2_LIB"); if (libname) handle = dlopen(libname, RTLD_LAZY); if (!handle) handle = dlopen("libgoto2.so", RTLD_LAZY); if (!handle) ERROR("%s", dlerror()); else INFO("%s loaded.", liftracc_plugin_info.name); char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); #ifdef _LIFTRACC_AUTOMODE_ strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #else /* _LIFTRACC_AUTOMODE_ */ strncat(plugin_data_filename, ".txt", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); #endif /* _LIFTRACC_AUTOMODE_ */ liftracc_selector_loadinfo(plugin_data_filename, &decision_data[0]); int i; for (i=0; i<GOTO_FUNCTIONS_COUNT; i++) { liftracc_plugin_fptr[i] = dlsym(handle, liftracc_goto_function_names[i]); } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_INIT])); #endif /* _LIFTRACC_PROFILING_ */ } void __attribute__ ((destructor)) liftracc_plugin_unload(void) { #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FINI])); #endif /* _LIFTRACC_PROFILING_ */ if (handle) dlclose(handle); handle = 0; #ifdef _LIFTRACC_AUTOMODE_TRAINING_ char plugin_data_filename[PATH_MAX]; Dl_info info; dladdr(liftracc_plugin_load, &info); strncpy(plugin_data_filename, info.dli_fname, PATH_MAX); strncat(plugin_data_filename, ".data", PATH_MAX-strlen(plugin_data_filename)-1); MSG("plugin_data_filename: %s", plugin_data_filename); liftracc_selector_saveinfo(plugin_data_filename, &decision_data[0]); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ INFO("%s unloaded.", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FINI])); print_profiling_data(liftracc_plugin_info.name, &(function_profiling_data[0]), liftracc_function_names, LIFTRACC_FUNCTIONS_COUNT); #endif /* _LIFTRACC_PROFILING_ */ } decision_data_t liftracc_plugin_getdecision(liftracc_selector_funcid_t id, int index) { #ifdef _LIFTRACC_AUTOMODE_ return decision_data[id*ARRAY_SIZE+index]; #else if (decision_data[id*ARRAY_SIZE+index] > 0) return decision_data[id*ARRAY_SIZE+index]; return liftracc_plugin_info.prio; #endif /* _LIFTRACC_AUTOMODE_ */ } /* START OF BLAS FUNCTION IMPLEMENTATION */ void liftracc_plugin_daxpy(const int n, const double alpha, const double * x, const int incx, double * y, const int incy) { INFO("%s_daxpy", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; void (*func)(); + *(void **) (&func) = liftracc_plugin_fptr[GOTO_DAXPY_ID]; - *(void **) (&func) = dlsym(handle, "cblas_daxpy"); - - if ((error = dlerror()) == 0) { + if (func != 0) { (*func)(n, alpha, x, incx, y, incy); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DAXPY])); #endif /* _LIFTRACC_PROFILING_ */ #if _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DAXPY, SELECT_DAXPY); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } double liftracc_plugin_ddot(const int n, const double *x, const int incx, const double *y, const int incy) { INFO("%s_ddot", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; + double ret = 0.0; double (*func)(); - *(void **) (&func) = dlsym(handle, "cblas_ddot"); + *(void **) (&func) = liftracc_plugin_fptr[GOTO_DDOT_ID]; - if ((error = dlerror()) != 0) { - ERROR("%s", error); - return 0.0; + if (func != 0) { + ret = (*func)(n, x, incx, y, incy); + } else { + success = 0; } - double ret = (*func)(n, x, incx, y, incy); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DDOT])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DDOT, SELECT_DDOT); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } void liftracc_plugin_dgemm(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc) { INFO("%s_dgemm", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; void (*func)(); - *(void **) (&func) = dlsym(handle, "cblas_dgemm"); + *(void **) (&func) = liftracc_plugin_fptr[GOTO_DGEMM_ID]; - if ((error = dlerror()) != 0) { - ERROR("%s", error); - return; + if (func != 0) { + (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + success = 0; } - (*func)(order, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DGEMM])); #endif /* _LIFTRACC_PROFILING_ */ #if _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DGEMM, SELECT_DGEMM); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } void liftracc_plugin_dscal(const int n, const double alpha, double * x, const int incx) { INFO("%s_dscal", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; void (*func)(); + *(void **) (&func) = liftracc_plugin_fptr[GOTO_DSCAL_ID]; - *(void **) (&func) = dlsym(handle, "cblas_dscal"); - - if ((error = dlerror()) == 0) { + if (func != 0) { (*func)(n, alpha, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_DSCAL])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_DSCAL, SELECT_DSCAL); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ } liftracc_index_t liftracc_plugin_idamax(const int n, const double * x, const int incx) { INFO("%s_idamax", liftracc_plugin_info.name); #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_start(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ + int success = 1; + liftracc_index_t ret = 0; liftracc_index_t (*func)(); - liftracc_index_t ret = 0.0; - - *(void **) (&func) = dlsym(handle, "cblas_idamax"); + *(void **) (&func) = liftracc_plugin_fptr[GOTO_IDAMAX_ID]; - if ((error = dlerror()) == 0) { + if (func != 0) { ret = (*func)(n, x, incx); + } else { + success = 0; } #if _LIFTRACC_PROFILING_ == 3 liftracc_function_timing_stop(&(function_profiling_data[LIFTRACC_FUNCTION_IDAMAX])); #endif /* _LIFTRACC_PROFILING_ */ #ifdef _LIFTRACC_AUTOMODE_TRAINING_ - set_decision_data(&decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); + set_decision_data(success, &decision_data[0], &function_profiling_data[0], n, LIFTRACC_FUNCTION_IDAMAX, SELECT_IDAMAX); #endif /* _LIFTRACC_AUTOMODE_TRAINING_ */ return ret; } diff --git a/library/tests/test05.cpp b/library/tests/test05.cpp index 9a11e4d..2ad7af8 100644 --- a/library/tests/test05.cpp +++ b/library/tests/test05.cpp @@ -1,113 +1,118 @@ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <math.h> #ifndef __USE_GNU #define __USE_GNU #endif #include <dlfcn.h> #include "liftracc.h" #include "liftracc_logging.h" #include "liftracc_profiling.h" extern "C" { #include "cblas.h" } int main(int argc, char** argv) { - printf("TEST\n"); #ifdef _LIFTRACC_PROFILING_ for (int i=0; i<100; i++) { liftracc_function_timing_start(&(liftracc_profiling_data[MEASURING_ERROR])); liftracc_function_timing_stop(&(liftracc_profiling_data[MEASURING_ERROR])); } #endif /* _LIFTRACC_PROFILING_ */ unsigned int error_count = 0; const int max_runs = 10; const int max_dim = 1024; //8192; const int max_entries = max_dim * max_dim; #ifdef _LIFTRACC_PROFILING_ profiling_data_t data[max_dim] = { }; #endif /* _LIFTRACC_PROFILING_ */ double *dA = (double*) malloc( sizeof(double) * max_entries ); double *dB = (double*) malloc( sizeof(double) * max_entries ); double *dC = (double*) malloc( sizeof(double) * max_entries ); double *dM = (double*) malloc( sizeof(double) * max_entries ); double dAlpha = 1.3; double dBeta = 3.7; srand(time(0)); // init libraries void *cblas_handle = 0; char *error = 0; - cblas_handle = dlopen("libcblas.so", RTLD_LAZY); + cblas_handle = dlopen("libcblas_inner.so", RTLD_LAZY); if (!cblas_handle) ERROR("%s", dlerror()); if (cblas_handle) INFO("lib init ok."); // function init void (*cblas_dgemm)(const liftracc_order_t order, const liftracc_transpose_t transa, const liftracc_transpose_t transb, const int m, const int n, const int k, const double alpha, const double *a, const int lda, const double *b, const int ldb, const double beta, double *c, const int ldc); *(void **) (&cblas_dgemm) = dlsym(cblas_handle, "inner_cblas_dgemm"); if ((error = dlerror()) != 0) { ERROR("%s", error); } // benchmark int j,i; for (j=0;j<max_runs;j++) { for (i=0; i<max_entries; i++) dA[i] = (double)(rand()%500/100.0); for (i=0; i<max_entries; i++) dB[i] = (double)(rand()%500/100.0); for (i=0; i<max_entries; i++) dM[i] = (double)(rand()%500/100.0); memcpy(dC, dM, max_entries); for (i=2; i<max_dim; i++) { #ifdef _LIFTRACC_PROFILING_ liftracc_function_timing_start(&(data[i])); #endif /* _LIFTRACC_PROFILING_ */ (*cblas_dgemm)(liftracc_col_major, liftracc_no_trans, liftracc_no_trans, i,i,i, dAlpha, dA, i, dB, i, dBeta, dC, i); + int different = 0; + int c; + for (c=0; c<max_entries; c++) { + if (dM[c] != dC[c]) different++; + } + MSG("Entries: %d -- Different: %d -- Same: %d", max_entries, different, max_entries-different); #ifdef _LIFTRACC_PROFILING_ liftracc_function_timing_stop(&(data[i])); #endif /* _LIFTRACC_PROFILING_ */ memcpy(dC, dM, max_entries); MSG("%d_%d.run", j, i); } } #ifdef _LIFTRACC_PROFILING_ print_profiling_data("cblas_RESULT", &(data[0]), 0, max_dim); #endif /* _LIFTRACC_PROFILING_ */ return error_count; }
pc2/liftracc
f740775d57b1c9f292c04be75448518a53739f82
missed some gitignores
diff --git a/.gitignore b/.gitignore index 4c5f08a..32b8a02 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ library/build/* +benchmarks/build/* +testapps/build/*
pc2/liftracc
2aa1c87168d839979c0ccaddf37f17ae9f8e3fac
github generated gh-pages branch
diff --git a/index.html b/index.html new file mode 100644 index 0000000..908c541 --- /dev/null +++ b/index.html @@ -0,0 +1,78 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + + <title>pc2/liftracc @ GitHub</title> + + <style type="text/css"> + body { + margin-top: 1.0em; + background-color: #e1ca9d; + font-family: "Helvetica,Arial,FreeSans"; + color: #000000; + } + #container { + margin: 0 auto; + width: 700px; + } + h1 { font-size: 3.8em; color: #1e3562; margin-bottom: 3px; } + h1 .small { font-size: 0.4em; } + h1 a { text-decoration: none } + h2 { font-size: 1.5em; color: #1e3562; } + h3 { text-align: center; color: #1e3562; } + a { color: #1e3562; } + .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;} + .download { float: right; } + pre { background: #000; color: #fff; padding: 15px;} + hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} + .footer { text-align:center; padding-top:30px; font-style: italic; } + </style> + +</head> + +<body> + <a href="http://github.com/pc2/liftracc"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> + + <div id="container"> + + <div class="download"> + <a href="http://github.com/pc2/liftracc/zipball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a> + <a href="http://github.com/pc2/liftracc/tarball/master"> + <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a> + </div> + + <h1><a href="http://github.com/pc2/liftracc">liftracc</a> + <span class="small">by <a href="http://github.com/pc2">pc2</a></span></h1> + + <div class="description"> + Dynamic Shared Library Interposing Framework for Transparent Accelerator Utilization + </div> + + <h2>Contact</h2> +<p>Paderborn Center for Parallel Computing</p> + + + <h2>Download</h2> + <p> + You can download this project in either + <a href="http://github.com/pc2/liftracc/zipball/master">zip</a> or + <a href="http://github.com/pc2/liftracc/tarball/master">tar</a> formats. + </p> + <p>You can also clone the project with <a href="http://git-scm.com">Git</a> + by running: + <pre>$ git clone git://github.com/pc2/liftracc</pre> + </p> + + <div class="footer"> + get the source code on GitHub : <a href="http://github.com/pc2/liftracc">pc2/liftracc</a> + </div> + + </div> + + +</body> +</html>
dyoo/js-numbers
2cf776f6017858a30488a4ec768be3e67bb0a6c4
use strict
diff --git a/src/js-numbers.js b/src/js-numbers.js index f8294ce..850d506 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,550 +1,551 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { + 'use strict'; // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(expandExponent(x+'')); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; var expandExponent = function(s) { var match = s.match(scientificPattern), mantissaChunks, exponent; if (match) { mantissaChunks = match[1].match(/^([^.]*)(.*)$/); exponent = Number(match[2]); if (mantissaChunks[2].length === 0) { return mantissaChunks[1] + zfill(exponent); } if (exponent >= mantissaChunks[2].length - 1) { return (mantissaChunks[1] + mantissaChunks[2].substring(1) + zfill(exponent - (mantissaChunks[2].length - 1))); } else { return (mantissaChunks[1] + mantissaChunks[2].substring(1, 1+exponent)); } } else { return s; } }; // zfill: integer -> string // builds a string of "0"'s of length n. var zfill = function(n) { var buffer = []; buffer.length = n; for (var i = 0; i < n; i++) { buffer[i] = '0'; } return buffer.join(''); }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = function(x, y) { var sum; if (typeof(x) === 'number' && typeof(y) === 'number') { sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } } if (x instanceof FloatPoint && y instanceof FloatPoint) { return x.add(y); } return addSlow(x, y); }; var addSlow = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = function(x, y) { var prod; if (typeof(x) === 'number' && typeof(y) === 'number') { prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } } if (x instanceof FloatPoint && y instanceof FloatPoint) { return x.multiply(y); } return multiplySlow(x, y); }; var multiplySlow = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isXSpecialCase: function(x) { return (eqv(x, 0)); }, onXSpecialCase: function(x, y) { if (eqv(y, 0)) { throwRuntimeError("/: division by zero", x, y); } return 0; }, isYSpecialCase: function(y) { return (eqv(y, 0)); }, onYSpecialCase: function(x, y) { throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; }
dyoo/js-numbers
d23ccf19cb36bff5786688680b4a707fc9c1b3f9
trying to fast-path a few common functions
diff --git a/src/js-numbers.js b/src/js-numbers.js index 0192b47..f8294ce 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,799 +1,828 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(expandExponent(x+'')); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; var expandExponent = function(s) { var match = s.match(scientificPattern), mantissaChunks, exponent; if (match) { mantissaChunks = match[1].match(/^([^.]*)(.*)$/); exponent = Number(match[2]); if (mantissaChunks[2].length === 0) { return mantissaChunks[1] + zfill(exponent); } if (exponent >= mantissaChunks[2].length - 1) { return (mantissaChunks[1] + mantissaChunks[2].substring(1) + zfill(exponent - (mantissaChunks[2].length - 1))); } else { return (mantissaChunks[1] + mantissaChunks[2].substring(1, 1+exponent)); } } else { return s; } }; // zfill: integer -> string // builds a string of "0"'s of length n. var zfill = function(n) { var buffer = []; buffer.length = n; for (var i = 0; i < n; i++) { buffer[i] = '0'; } return buffer.join(''); }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number - var add = makeNumericBinop( + var add = function(x, y) { + var sum; + if (typeof(x) === 'number' && typeof(y) === 'number') { + sum = x + y; + if (isOverflow(sum)) { + return (makeBignum(x)).add(makeBignum(y)); + } + } + if (x instanceof FloatPoint && y instanceof FloatPoint) { + return x.add(y); + } + return addSlow(x, y); + }; + + var addSlow = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number - var multiply = makeNumericBinop( + var multiply = function(x, y) { + var prod; + if (typeof(x) === 'number' && typeof(y) === 'number') { + prod = x * y; + if (isOverflow(prod)) { + return (makeBignum(x)).multiply(makeBignum(y)); + } else { + return prod; + } + } + if (x instanceof FloatPoint && y instanceof FloatPoint) { + return x.multiply(y); + } + return multiplySlow(x, y); + }; + var multiplySlow = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isXSpecialCase: function(x) { return (eqv(x, 0)); }, onXSpecialCase: function(x, y) { if (eqv(y, 0)) { throwRuntimeError("/: division by zero", x, y); } return 0; }, isYSpecialCase: function(y) { return (eqv(y, 0)); }, onYSpecialCase: function(x, y) { throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (! isInteger(x)) { throwRuntimeError('integer-sqrt: the argument ' + x.toString() + " is not an integer.", x); } if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2);
dyoo/js-numbers
608b38f21c53684e4310ad36b06bf47c1a4f4fc3
changing the behavior of tan, atan, and makeComplexPolar when given exact 0
diff --git a/src/js-numbers.js b/src/js-numbers.js index bfe4a28..0192b47 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -107,1216 +107,1218 @@ if (typeof(exports) !== 'undefined') { mantissaChunks[2].substring(1, 1+exponent)); } } else { return s; } }; // zfill: integer -> string // builds a string of "0"'s of length n. var zfill = function(n) { var buffer = []; buffer.length = n; for (var i = 0; i < n; i++) { buffer[i] = '0'; } return buffer.join(''); }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isXSpecialCase: function(x) { return (eqv(x, 0)); }, onXSpecialCase: function(x, y) { if (eqv(y, 0)) { throwRuntimeError("/: division by zero", x, y); } return 0; }, isYSpecialCase: function(y) { return (eqv(y, 0)); }, onYSpecialCase: function(x, y) { throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { + if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { + if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (! isInteger(x)) { throwRuntimeError('integer-sqrt: the argument ' + x.toString() + " is not an integer.", x); } if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. - if (equals(theta, 0)) { + if (eqv(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d));
dyoo/js-numbers
185e321241353ba9f958491265baab84c4734dd4
fixing bug: asin(0) = exact 0
diff --git a/src/js-numbers.js b/src/js-numbers.js index a0ceac9..bfe4a28 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -150,1024 +150,1025 @@ if (typeof(exports) !== 'undefined') { // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isXSpecialCase: function(x) { return (eqv(x, 0)); }, onXSpecialCase: function(x, y) { if (eqv(y, 0)) { throwRuntimeError("/: division by zero", x, y); } return 0; }, isYSpecialCase: function(y) { return (eqv(y, 0)); }, onYSpecialCase: function(x, y) { throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { + if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (! isInteger(x)) { throwRuntimeError('integer-sqrt: the argument ' + x.toString() + " is not an integer.", x); } if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. diff --git a/test/tests.js b/test/tests.js index 2506cff..b27943a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -3065,861 +3065,860 @@ describe('integerSqrt', { integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); assertTrue(eqv(integerSqrt(negative_zero), negative_zero)); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('repeating decimals', { tests: function() { assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); }, limitRendering: function() { var OPTIONS = {limit: 5}; assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1, OPTIONS)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2, OPTIONS)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3, OPTIONS)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4, OPTIONS)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5, OPTIONS)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6, OPTIONS)); assertEquals(['0', '05882', '...'], toRepeatingDecimal(1, 17, {limit : 5})); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8, {limit : 4})); assertEquals(['0', '125', '...'], toRepeatingDecimal(1, 8, {limit : 3})); assertEquals(['0', '12', '...'], toRepeatingDecimal(1, 8, {limit : 2})); assertEquals(['0', '1', '...'], toRepeatingDecimal(1, 8, {limit : 1})); assertEquals(['0', '', '...'], toRepeatingDecimal(1, 8, {limit : 0})); assertEquals(['10012718086', '8577149703838870007766167', '...'], toRepeatingDecimal(makeBignum("239872983562893234879"), makeBignum("23956829852"), {limit:25})); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertEqv(divide(makeFloat(1),makeFloat(0)), inf); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ - assertTrue(equals(asin(0), - 0)); + assertTrue(eqv(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(diffPercent(realPart(asin(makeComplex(1, 5))), makeFloat(0.1937931365549321)) < 1e-2); assertTrue(diffPercent(imaginaryPart(asin(makeComplex(1, 5))), makeFloat(2.3309746530493123)) < 1e-2); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); assertEquals("5.0+0.0i", (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", (makeComplex(5, 1)).toString()); assertEquals("4-2i", (makeComplex(4, -2)).toString()); }, testQuotient : function(){ assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(36), makeRational(7)), makeRational(5))); assertTrue(eqv(1, quotient(7, 5))); }, testRemainder : function(){ assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, modulo(n1, n2)); assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(isReal(pi)); assertTrue(isReal(1)); assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!isReal("hi")); }, testRound : function(){ assertTrue(equals(round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(round(makeRational(3)), makeRational(3))); assertTrue(equals(round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(round(makeRational(-17, 4)), makeRational(-4))); }, // testSgn : function(){ // assertTrue(equals(sgn(makeFloat(4)), 1)); // assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); // assertTrue(equals(sgn(0), 0)); // }, // testZero_question_ : function(){ // assertTrue(Kernel.zero_question_(0)); // assertTrue(!Kernel.zero_question_(1)); // assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); // } });
dyoo/js-numbers
d7fd36e5ace3c74a59182dff5723e78491453a99
added another test case
diff --git a/test/tests.js b/test/tests.js index 34b7e2b..2506cff 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,679 +1,681 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertEqv = function(x, y) { value_of(eqv(x, y)).should_be_true(); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); value_of(toFixnum(makeRational(1, 5)) === 0.2) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { assertTrue(eqv(makeComplexPolar(1, 2), makeComplex(makeFloat(-0.4161468365471424), makeFloat(0.9092974268256817)))); }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); + assertEquals(makeFloat(1000000000000000.2), + fromString("1000000000000000.2")); assertEquals(makeFloat(10000000000000000.2), fromString("10000000000000000.2")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertTrue(equals(fromString("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100))); assertTrue(equals(fromString("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200))); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(makeRational(1024), makeFloat(1024))).should_be_false(); value_of(eqv(makeRational(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { // If any component of a complex is inexact, both // the real and imaginary parts get turned into // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); assertFalse(isRational(makeComplex(makeFloat(0), makeFloat(0)))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723")));
dyoo/js-numbers
b3d6f8b8e1a9bc67d360fec14e0124f06a47ade6
Passing test cases again
diff --git a/README b/README index dc9bcd2..28f28a5 100644 --- a/README +++ b/README @@ -1,320 +1,324 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a toplevel namespace called jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number - Convert from a javascript number to a scheme-number. + Convert from a javascript number to a scheme number. If the + number looks like an integer, represents as an exact integer. + Otherwise, represents as a float. If you need more precision over + the representation, use makeFloat or makeRational instead. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes - the denominator is 1. + the denominator is 1. The numerator and denominator must be + integers. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInexact: scheme-number -> boolean Produces true if the number is inexact. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. toInexact: scheme-number -> scheme-number Converts the number to an inexact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. quotient: scheme-number scheme-number -> scheme-number Produces the quotient. Both inputs must be integers. remainder: scheme-number scheme-number -> scheme-number Produces the remainder. Both inputs must be integers. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. toRepeatedDecimal: scheme-number scheme-number {limit: number}? -> [string, string, string] Produces a string representation of the decimal expansion; the first and second argument must be integers. Returns an array of three parts: the portion before the decimal, the non-repeating part, and then the repeating part. If the expansion goes beyond the limit (by default, 256 characters), then the expansion will be cut off, and the third portion will be '...'. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, sgn * Add real documentation. ====================================================================== Related work There appears to be another Scheme numeric tower implementation that just came out in the last month or so, by Matt Might and John Tobey: https://github.com/jtobey/javascript-bignum http://silentmatt.com/biginteger/ ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. June 2010: got implementation of integer-sqrt from Ugur Cekmez; brought in some fixes from Ethan Cecchetti. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index e1f0f4c..a0ceac9 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,600 +1,634 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { - if (isOverflow(nf)) { - return makeBignum(x); - } else { + if (isOverflow(nf)) { + return makeBignum(expandExponent(x+'')); + } else { return nf; } } else { - return FloatPoint.makeInstance(x); + return FloatPoint.makeInstance(x); + } + }; + + var expandExponent = function(s) { + var match = s.match(scientificPattern), mantissaChunks, exponent; + if (match) { + mantissaChunks = match[1].match(/^([^.]*)(.*)$/); + exponent = Number(match[2]); + + if (mantissaChunks[2].length === 0) { + return mantissaChunks[1] + zfill(exponent); + } + + if (exponent >= mantissaChunks[2].length - 1) { + return (mantissaChunks[1] + + mantissaChunks[2].substring(1) + + zfill(exponent - (mantissaChunks[2].length - 1))); + } else { + return (mantissaChunks[1] + + mantissaChunks[2].substring(1, 1+exponent)); + } + } else { + return s; + } + }; + + // zfill: integer -> string + // builds a string of "0"'s of length n. + var zfill = function(n) { + var buffer = []; + buffer.length = n; + for (var i = 0; i < n; i++) { + buffer[i] = '0'; } + return buffer.join(''); }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isXSpecialCase: function(x) { return (eqv(x, 0)); }, onXSpecialCase: function(x, y) { if (eqv(y, 0)) { throwRuntimeError("/: division by zero", x, y); } return 0; }, isYSpecialCase: function(y) { return (eqv(y, 0)); }, onYSpecialCase: function(x, y) { throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { @@ -988,1885 +1022,1887 @@ if (typeof(exports) !== 'undefined') { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { - return fromFixnum(fl); + return fl; } else { - return fromFixnum(ce); + return ce; } } else { - return fromFixnum(Math.round(this.n / this.d)); + return Math.round(this.n / this.d); } }; - Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(-0.0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } else if (n === 0) { if ((1/n) === -Infinity) { return NEGATIVE_ZERO; } else { return INEXACT_ZERO; } } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n - other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { return FloatPoint.makeInstance(this.n * other.n); }; FloatPoint.prototype.divide = function(other) { return FloatPoint.makeInstance(this.n / other.n); }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { return FloatPoint.makeInstance(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } - if (typeof(r) === 'number') { r = fromFixnum(r); } - if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } if (this.isInexact() || other.isInexact()) { // http://portal.acm.org/citation.cfm?id=1039814 // We currently use Smith's method, though we should // probably switch over to Priest's method. a = this.r; b = this.i; c = other.r; d = other.i; if (lessThanOrEqual(abs(d), abs(c))) { r = divide(d, c); x = divide(add(a, multiply(b, r)), add(c, multiply(d, r))); y = divide(subtract(b, multiply(a, r)), add(c, multiply(d, r))); } else { r = divide(c, d); x = divide(add(multiply(a, r), b), add(multiply(c, r), d)); y = divide(subtract(multiply(b, r), a), add(multiply(c, r), d)); } return Complex.makeInstance(x, y); } else { var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); - var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); - var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); - var digitRegexp = new RegExp("\\d"); + var digitRegexp = new RegExp("^[+-]?\\d+$"); + var flonumRegexp = new RegExp("^([+-]?\\d*)\\.(\\d*)$"); + var scientificPattern = new RegExp("^([+-]?\\d*\\.?\\d*)[Ee](\\+?\\d+)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } + // Floating point tests if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } - if (x.match(digitRegexp) && - (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { + if (x.match(flonumRegexp) || x.match(scientificPattern)) { + return FloatPoint.makeInstance(Number(x)); + } + + // Finally, integer tests. + if (x.match(digitRegexp)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { - return fromFixnum(n); + return n; } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry @@ -3110,949 +3146,944 @@ if (typeof(exports) !== 'undefined') { // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } // (public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } // (public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } // (public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } // (protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]+a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } - var match = s.match(bignumScientificPattern); - if (match) { - return new BigInteger(match[1]+match[2] + - zerostring(Number(match[3]) - match[2].length), - 10); - } else { - return new BigInteger(s, 10); - } + s = expandExponent(s); + return new BigInteger(s, 10); }; + var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1))))) { guess = floor(divide(add(guess, floor(divide(n, guess))), 2)); } return guess; }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { var n; if(sign(this) >= 0) { return searchIter(this, this); } else { n = this.negate(); return Complex.makeInstance(0, searchIter(n, n)); } }; })(); (function() { // Get an approximation using integerSqrt, and then start another // Newton-Ralphson search if necessary. BigInteger.prototype.sqrt = function() { var approx = this.integerSqrt(), fix; if (eqv(sqr(approx), this)) { return approx; } fix = toFixnum(this); if (isFinite(fix)) { if (fix >= 0) { return FloatPoint.makeInstance(Math.sqrt(fix)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-fix))); } } else { return approx; } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. // // An optional limit on the decimal expansion can be provided, in which // case the search cuts off if we go past the limit. // If this happens, the third argument returned becomes '...' to indicate // that the search was prematurely cut off. var toRepeatingDecimal = (function() { var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { if (limit-- <= 0) { return [digits.join(''), '...'] } var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d, options) { // default limit on decimal expansion; can be overridden var limit = 512; if (options && typeof(options.limit) !== 'undefined') { limit = options.limit; } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; // The following exposes the class representations for easier // integration with other projects. Numbers['BigInteger'] = BigInteger; Numbers['Rational'] = Rational; Numbers['FloatPoint'] = FloatPoint; Numbers['Complex'] = Complex; Numbers['MIN_FIXNUM'] = MIN_FIXNUM; Numbers['MAX_FIXNUM'] = MAX_FIXNUM; })(); diff --git a/test/tests.js b/test/tests.js index c5cebc9..34b7e2b 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,1036 +1,1036 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertEqv = function(x, y) { value_of(eqv(x, y)).should_be_true(); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); value_of(toFixnum(makeRational(1, 5)) === 0.2) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { assertTrue(eqv(makeComplexPolar(1, 2), makeComplex(makeFloat(-0.4161468365471424), makeFloat(0.9092974268256817)))); }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); - assertEquals(makeFloat(0.1), fromString(".1")); - assertEquals(makeFloat(0.23), fromString("0.23")); - assertEquals(makeFloat(0.1), fromString("+.1")); - assertEquals(makeFloat(-0.1), fromString("-.1")); - assertEquals(makeFloat(-0.123423), fromString("-.123423")); - assertEquals(makeFloat(123.45), fromString("123.45")); - assertEquals(makeFloat(4123.423), fromString("4.123423e3")); - assertEquals(makeFloat(10000000000000000.2), - fromString("10000000000000000.2")); + assertEquals(makeFloat(0.1), fromString(".1")); + assertEquals(makeFloat(0.23), fromString("0.23")); + assertEquals(makeFloat(0.1), fromString("+.1")); + assertEquals(makeFloat(-0.1), fromString("-.1")); + assertEquals(makeFloat(-0.123423), fromString("-.123423")); + assertEquals(makeFloat(123.45), fromString("123.45")); + assertEquals(makeFloat(4123.423), fromString("4.123423e3")); + assertEquals(makeFloat(10000000000000000.2), + fromString("10000000000000000.2")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { - assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - fromFixnum(10e100)); + assertTrue(equals(fromString("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + fromFixnum(10e100))); - assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - fromFixnum(10e200)); + assertTrue(equals(fromString("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + fromFixnum(10e200))); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { - value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); - value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); + value_of(eqv(makeRational(1024), makeFloat(1024))).should_be_false(); + value_of(eqv(makeRational(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { // If any component of a complex is inexact, both // the real and imaginary parts get turned into // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); assertFalse(isRational(makeComplex(makeFloat(0), makeFloat(0)))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723"))); assertTrue(isReal(makeBignum("1e1000"))); assertTrue(isReal(makeBignum("-1e1000"))); assertTrue(isReal(makeBignum("1e23784"))); assertTrue(isReal(makeBignum("-7.241e23784"))); }, 'rationals': function() { assertTrue(isReal(makeRational(0, 1))); assertTrue(isReal(makeRational(0, 12342))); assertTrue(isReal(makeRational(-2324, 12342))); assertTrue(isReal(makeRational(1, 2))); }, 'floats': function() { assertTrue(isReal(makeFloat(1.0))); assertTrue(isReal(makeFloat(25.0))); assertTrue(isReal(e)); assertTrue(isReal(pi)); assertTrue(isReal(inf)); assertTrue(isReal(negative_inf)); assertTrue(isReal(nan)); }, 'complex': function() { assertTrue(isReal(makeComplex(0, 0))); assertTrue(isReal(makeComplex(e, 0))); assertTrue(isReal(makeComplex(pi, 0))); assertTrue(isReal(makeComplex(nan, 0))); assertTrue(isReal(makeComplex(inf, 0))); assertTrue(isReal(makeComplex(negative_inf, 0))); assertFalse(isReal(makeComplex(0, 1))); assertFalse(isReal(makeComplex(0, negative_inf))); assertFalse(isReal(makeComplex(pi, inf))); assertFalse(isReal(makeComplex(234, nan))); assertFalse(isReal(makeComplex(makeFloat(3), makeFloat(0)))); }, 'others': function() { assertFalse(isReal("0")); assertFalse(isReal("hello")); assertFalse(isReal([])); assertFalse(isReal({})); assertFalse(isReal(false)); } }); describe('isExact', { 'fixnums': function() { assertTrue(isExact(19)); assertTrue(isExact(0)); assertTrue(isExact(-1)); assertTrue(isExact(1)); }, 'bignums': function() { assertTrue(isExact(makeBignum("0"))); assertTrue(isExact(makeBignum("1"))); assertTrue(isExact(makeBignum("-1"))); assertTrue(isExact(makeBignum("23497842398287924789232439723"))); assertTrue(isExact(makeBignum("1e1000"))); assertTrue(isExact(makeBignum("-1e1000"))); assertTrue(isExact(makeBignum("12342357892297851728921374891327893"))); assertTrue(isExact(makeBignum("4.1321e200"))); assertTrue(isExact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertTrue(isExact(makeRational(19))); assertTrue(isExact(makeRational(0))); assertTrue(isExact(makeRational(-1))); assertTrue(isExact(makeRational(1))); assertTrue(isExact(makeRational(1, 2))); assertTrue(isExact(makeRational(1, 29291))); }, 'floats': function() { assertFalse(isExact(e)); assertFalse(isExact(pi)); assertFalse(isExact(inf)); assertFalse(isExact(negative_inf)); assertFalse(isExact(nan)); assertFalse(isExact(makeFloat(0))); assertFalse(isExact(makeFloat(1111.1))); }, 'complex': function() { assertTrue(isExact(makeComplex(0, 0))); assertTrue(isExact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertFalse(isExact(makeComplex(e, makeRational(1, 17)))); assertFalse(isExact(makeComplex(makeRational(1,2), pi))); assertFalse(isExact(makeComplex(makeRational(1,2), nan))); assertFalse(isExact(makeComplex(negative_inf, nan))); } }); describe('isInexact', { 'fixnums': function() { assertFalse(isInexact(19)); assertFalse(isInexact(0)); assertFalse(isInexact(-1)); assertFalse(isInexact(1)); }, 'bignums': function() { assertFalse(isInexact(makeBignum("0"))); assertFalse(isInexact(makeBignum("1"))); assertFalse(isInexact(makeBignum("-1"))); assertFalse(isInexact(makeBignum("23497842398287924789232439723"))); assertFalse(isInexact(makeBignum("1e1000"))); assertFalse(isInexact(makeBignum("-1e1000"))); assertFalse(isInexact(makeBignum("12342357892297851728921374891327893"))); assertFalse(isInexact(makeBignum("4.1321e200"))); assertFalse(isInexact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertFalse(isInexact(makeRational(19))); assertFalse(isInexact(makeRational(0))); assertFalse(isInexact(makeRational(-1))); assertFalse(isInexact(makeRational(1))); assertFalse(isInexact(makeRational(1, 2))); assertFalse(isInexact(makeRational(1, 29291))); }, 'floats': function() { assertTrue(isInexact(e)); assertTrue(isInexact(pi)); assertTrue(isInexact(inf)); assertTrue(isInexact(negative_inf)); assertTrue(isInexact(nan)); assertTrue(isInexact(makeFloat(0))); assertTrue(isInexact(makeFloat(1111.1))); }, 'complex': function() { assertFalse(isInexact(makeComplex(0, 0))); assertFalse(isInexact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertTrue(isInexact(makeComplex(e, makeRational(1, 17)))); assertTrue(isInexact(makeComplex(makeRational(1,2), pi))); assertTrue(isInexact(makeComplex(makeRational(1,2), nan))); assertTrue(isInexact(makeComplex(negative_inf, nan))); } }); describe('isInteger', { 'fixnums': function() { assertTrue(isInteger(1)); assertTrue(isInteger(-1)); }, 'bignums': function() { assertTrue(isInteger(makeBignum("2983473189472187414789132743928148151617364"))); assertTrue(isInteger(makeBignum("-99999999999999999999999999999999999999"))); }, 'rationals': function() { assertTrue(isInteger(makeRational(1, 1))); assertFalse(isInteger(makeRational(1, 2))); assertFalse(isInteger(makeRational(9999, 10000))); assertFalse(isInteger(makeRational(9999, 1000))); }, 'floats': function() { assertFalse(isInteger(makeFloat(2.3))); assertTrue(isInteger(makeFloat(4.0))); assertFalse(isInteger(inf)); assertFalse(isInteger(negative_inf)); assertFalse(isInteger(nan)); }, 'complex': function() { assertTrue(isInteger(makeComplex(42, 0))); assertFalse(isInteger(makeComplex(makeFloat(42), makeFloat(0)))); assertFalse(isInteger(makeComplex(42, 42))); assertFalse(isInteger(i)); assertFalse(isInteger(negative_i)); }, 'others': function() { assertFalse(isInteger("hello")); assertFalse(isInteger("0")); } }); describe('toFixnum', { 'fixnums': function() { assertEquals(42, toFixnum(42)); assertEquals(-20, toFixnum(-20)); assertEquals(0, toFixnum(0)); }, 'bignums': function() { assertEquals(123456789, toFixnum(makeBignum("123456789"))); assertEquals(0, toFixnum(makeBignum("0"))); assertEquals(-123, toFixnum(makeBignum("-123"))); assertEquals(123456, toFixnum(makeBignum("123456"))); // We're dealing with big numbers, where the numerical error // makes it difficult to compare for equality. We just go for // percentage and see that it is ok. assertTrue(diffPercent(1e200, toFixnum(makeBignum("1e200"))) < 1e-10); assertTrue(diffPercent(-1e200, toFixnum(makeBignum("-1e200"))) < 1e-10); }, 'rationals': function() { assertEquals(0, toFixnum(zero)); assertEquals(17/2, toFixnum(makeRational(17, 2))); assertEquals(1926/3, toFixnum(makeRational(1926, 3))); assertEquals(-11150/17, toFixnum(makeRational(-11150, 17))); }, 'floats': function() { assertEquals(12345.6789, toFixnum(makeFloat(12345.6789))); assertEquals(Math.PI, toFixnum(pi)); assertEquals(Math.E, toFixnum(e)); assertEquals(Number.POSITIVE_INFINITY, toFixnum(inf)); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(negative_inf)); assertTrue(isNaN(toFixnum(nan))); }, 'complex': function() { assertFails(function() { toFixnum(makeComplex(2, 1)); }); assertFails(function() { toFixnum(i); }); assertFails(function() { toFixnum(negative_i); }); assertEquals(2, toFixnum(makeComplex(2, 0))); assertEquals(1/2, toFixnum(makeComplex(makeRational(1, 2), 0))); assertEquals(Number.POSITIVE_INFINITY, toFixnum(makeComplex(inf, 0))); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(makeComplex(negative_inf, 0))); assertTrue(isNaN(toFixnum(makeComplex(nan, 0)))); } }); describe('toExact', { 'fixnums': function() { assertEquals(1792, toExact(1792)); assertEquals(0, toExact(0)); assertEquals(-1, toExact(-1)); }, 'bignums': function() { assertEquals(makeBignum("4.2e100"), toExact(makeBignum("4.2e100"))); assertEquals(makeBignum("0"), toExact(makeBignum("0"))); assertEquals(makeBignum("1"), toExact(makeBignum("1"))); assertEquals(makeBignum("-1"), toExact(makeBignum("-1"))); assertEquals(makeBignum("-12345"), toExact(makeBignum("-12345"))); assertEquals(makeBignum("-1.723e500"), toExact(makeBignum("-1.723e500"))); }, 'rationals': function() { assertEquals(makeRational(1, 2), toExact(makeRational(1, 2))); assertEquals(makeRational(1, 9999), toExact(makeRational(1, 9999))); assertEquals(makeRational(0, 1), toExact(makeRational(0, 9999))); assertEquals(makeRational(-290, 1), toExact(makeRational(-290, 1))); }, 'floats': function() { assertEquals(makeRational(1, 2), toExact(makeFloat(0.5))); assertEquals(makeRational(1, 10), toExact(makeFloat(0.1))); assertEquals(makeRational(9, 10), toExact(makeFloat(0.9))); assertTrue(isExact(toExact(makeFloat(10234.7)))); assertTrue(diffPercent(makeRational(102347, 10), toExact(makeFloat(10234.7))) < 1); assertEquals(-1, toExact(makeFloat(-1))); assertEquals(0, toExact(makeFloat(0))); assertEquals(1024, toExact(makeFloat(1024))); assertFails(function() { toExact(nan); }); assertFails(function() { toExact(inf); }); assertFails(function() { toExact(negative_inf); }); }, 'complex': function() { assertEquals(0, toExact(makeComplex(0, 0))); assertEquals(99, toExact(makeComplex(99, 0))); assertEquals(makeRational(-1, 2), toExact(makeComplex(makeRational(-1, 2), 0))); assertEquals(makeRational(1, 4), toExact(makeComplex(makeFloat(.25), 0))); assertFails(function() { toExact(makeComplex(nan, 0)); }); assertFails(function() { toExact(makeComplex(inf, 0)); }); assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); assertTrue(eqv(toExact(makeComplex(0, 1)), makeComplex(0, 1))); assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)),
dyoo/js-numbers
c8c4fbc63b73dadd8a45d37b6f2608ec9c4982d1
adding test case from report by manuel simoni
diff --git a/test/tests.js b/test/tests.js index 45b8654..c5cebc9 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,679 +1,681 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertEqv = function(x, y) { value_of(eqv(x, y)).should_be_true(); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); value_of(toFixnum(makeRational(1, 5)) === 0.2) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { assertTrue(eqv(makeComplexPolar(1, 2), makeComplex(makeFloat(-0.4161468365471424), makeFloat(0.9092974268256817)))); }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); + assertEquals(makeFloat(10000000000000000.2), + fromString("10000000000000000.2")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { // If any component of a complex is inexact, both // the real and imaginary parts get turned into // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); assertFalse(isRational(makeComplex(makeFloat(0), makeFloat(0)))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723"))); assertTrue(isReal(makeBignum("1e1000"))); assertTrue(isReal(makeBignum("-1e1000")));
dyoo/js-numbers
caaef42a23855fa05481710e06ee642f71de530e
exposing min and max fixnum constants as well
diff --git a/README b/README index e981b3c..dc9bcd2 100644 --- a/README +++ b/README @@ -1,322 +1,320 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a toplevel namespace called jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInexact: scheme-number -> boolean Produces true if the number is inexact. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. toInexact: scheme-number -> scheme-number Converts the number to an inexact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. quotient: scheme-number scheme-number -> scheme-number Produces the quotient. Both inputs must be integers. remainder: scheme-number scheme-number -> scheme-number Produces the remainder. Both inputs must be integers. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. toRepeatedDecimal: scheme-number scheme-number {limit: number}? -> [string, string, string] Produces a string representation of the decimal expansion; the first and second argument must be integers. Returns an array of three parts: the portion before the decimal, the non-repeating part, and then the repeating part. If the expansion goes beyond the limit (by default, 256 characters), then the expansion will be cut off, and the third portion will be '...'. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, sgn -* Bring over the numeric test cases from Moby. - * Add real documentation. ====================================================================== Related work There appears to be another Scheme numeric tower implementation that just came out in the last month or so, by Matt Might and John Tobey: https://github.com/jtobey/javascript-bignum http://silentmatt.com/biginteger/ ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. June 2010: got implementation of integer-sqrt from Ugur Cekmez; brought in some fixes from Ethan Cecchetti. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index c28d5bc..e1f0f4c 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3541,516 +3541,518 @@ if (typeof(exports) !== 'undefined') { BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1))))) { guess = floor(divide(add(guess, floor(divide(n, guess))), 2)); } return guess; }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { var n; if(sign(this) >= 0) { return searchIter(this, this); } else { n = this.negate(); return Complex.makeInstance(0, searchIter(n, n)); } }; })(); (function() { // Get an approximation using integerSqrt, and then start another // Newton-Ralphson search if necessary. BigInteger.prototype.sqrt = function() { var approx = this.integerSqrt(), fix; if (eqv(sqr(approx), this)) { return approx; } fix = toFixnum(this); if (isFinite(fix)) { if (fix >= 0) { return FloatPoint.makeInstance(Math.sqrt(fix)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-fix))); } } else { return approx; } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. // // An optional limit on the decimal expansion can be provided, in which // case the search cuts off if we go past the limit. // If this happens, the third argument returned becomes '...' to indicate // that the search was prematurely cut off. var toRepeatingDecimal = (function() { var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { if (limit-- <= 0) { return [digits.join(''), '...'] } var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d, options) { // default limit on decimal expansion; can be overridden var limit = 512; if (options && typeof(options.limit) !== 'undefined') { limit = options.limit; } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; // The following exposes the class representations for easier // integration with other projects. Numbers['BigInteger'] = BigInteger; Numbers['Rational'] = Rational; Numbers['FloatPoint'] = FloatPoint; - Numbers['Complex'] = Complex; - + Numbers['Complex'] = Complex; + + Numbers['MIN_FIXNUM'] = MIN_FIXNUM; + Numbers['MAX_FIXNUM'] = MAX_FIXNUM; })();
dyoo/js-numbers
11fcb0f7724dd247f15b68feb34c7472e5211a26
adding exports for Manuel Simoni
diff --git a/src/js-numbers.js b/src/js-numbers.js index 6064239..c28d5bc 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3534,513 +3534,523 @@ if (typeof(exports) !== 'undefined') { // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1))))) { guess = floor(divide(add(guess, floor(divide(n, guess))), 2)); } return guess; }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { var n; if(sign(this) >= 0) { return searchIter(this, this); } else { n = this.negate(); return Complex.makeInstance(0, searchIter(n, n)); } }; })(); (function() { // Get an approximation using integerSqrt, and then start another // Newton-Ralphson search if necessary. BigInteger.prototype.sqrt = function() { var approx = this.integerSqrt(), fix; if (eqv(sqr(approx), this)) { return approx; } fix = toFixnum(this); if (isFinite(fix)) { if (fix >= 0) { return FloatPoint.makeInstance(Math.sqrt(fix)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-fix))); } } else { return approx; } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. // // An optional limit on the decimal expansion can be provided, in which // case the search cuts off if we go past the limit. // If this happens, the third argument returned becomes '...' to indicate // that the search was prematurely cut off. var toRepeatingDecimal = (function() { var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { if (limit-- <= 0) { return [digits.join(''), '...'] } var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d, options) { // default limit on decimal expansion; can be overridden var limit = 512; if (options && typeof(options.limit) !== 'undefined') { limit = options.limit; } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; + + + // The following exposes the class representations for easier + // integration with other projects. + Numbers['BigInteger'] = BigInteger; + Numbers['Rational'] = Rational; + Numbers['FloatPoint'] = FloatPoint; + Numbers['Complex'] = Complex; + + })();
dyoo/js-numbers
69c9197adf1d0a96600d0bc82f746465669642ef
noting related work
diff --git a/README b/README index e9c9449..e981b3c 100644 --- a/README +++ b/README @@ -1,310 +1,322 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a toplevel namespace called jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInexact: scheme-number -> boolean Produces true if the number is inexact. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. toInexact: scheme-number -> scheme-number Converts the number to an inexact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. quotient: scheme-number scheme-number -> scheme-number Produces the quotient. Both inputs must be integers. remainder: scheme-number scheme-number -> scheme-number Produces the remainder. Both inputs must be integers. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. toRepeatedDecimal: scheme-number scheme-number {limit: number}? -> [string, string, string] Produces a string representation of the decimal expansion; the first and second argument must be integers. Returns an array of three parts: the portion before the decimal, the non-repeating part, and then the repeating part. If the expansion goes beyond the limit (by default, 256 characters), then the expansion will be cut off, and the third portion will be '...'. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, sgn * Bring over the numeric test cases from Moby. * Add real documentation. +====================================================================== + +Related work + +There appears to be another Scheme numeric tower implementation that +just came out in the last month or so, by Matt Might and John Tobey: + + https://github.com/jtobey/javascript-bignum + http://silentmatt.com/biginteger/ + + + ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. June 2010: got implementation of integer-sqrt from Ugur Cekmez; brought in some fixes from Ethan Cecchetti. \ No newline at end of file
dyoo/js-numbers
e5bdeaa4edb66c4e6968d4810f7561ed820fa0da
removing deprecated comment
diff --git a/src/js-numbers.js b/src/js-numbers.js index 0af77b0..6064239 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -832,1026 +832,1024 @@ if (typeof(exports) !== 'undefined') { // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; - // FIXME: up to this point I've modified Rational to use the _integer functions. - // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(-0.0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } else if (n === 0) { if ((1/n) === -Infinity) { return NEGATIVE_ZERO; } else { return INEXACT_ZERO; } } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n - other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { return FloatPoint.makeInstance(this.n * other.n); }; FloatPoint.prototype.divide = function(other) { return FloatPoint.makeInstance(this.n / other.n); }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { return FloatPoint.makeInstance(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); };
dyoo/js-numbers
d6afb0468bff83bc783efe49621d81da207a6614
fallback on biginteger.sqrt: just switch over to floating point if we can't get the exact answer
diff --git a/src/js-numbers.js b/src/js-numbers.js index eec0d97..0af77b0 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3240,841 +3240,809 @@ if (typeof(exports) !== 'undefined') { function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { - while(!(goodEnough(n, guess))) { - guess = average(guess, - floor(divide(n, guess))); + while(!(lessThanOrEqual(sqr(guess),n) && + lessThan(n,sqr(add(guess, 1))))) { + guess = floor(divide(add(guess, + floor(divide(n, guess))), + 2)); } return guess; }; - - var average = function (x,y) { - return floor(divide(add(x,y), 2)); - }; - - var goodEnough = function(n, guess) { - return (lessThanOrEqual(sqr(guess),n) && - lessThan(n,sqr(add(guess, 1)))); - }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { - if(this.s == 0) { + var n; + if(sign(this) >= 0) { return searchIter(this, this); } else { - var tmpThis = multiply(this, -1); - return Complex.makeInstance(0, - searchIter(tmpThis, tmpThis)); + n = this.negate(); + return Complex.makeInstance(0, searchIter(n, n)); } }; })(); - (function() { - - - // Classic implementation of Newton-Ralphson square-root search. - // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number - var searchIter = function(n, guess) { - var maxIterations = 100; - while(Math.abs(guess*guess - n) > 0.000001 && - (maxIterations--) > 0) { - guess = (guess + n/guess) / 2 - - } - return guess; - }; - + (function() { // Get an approximation using integerSqrt, and then start another // Newton-Ralphson search if necessary. BigInteger.prototype.sqrt = function() { - var approx = this.integerSqrt(); - var f; + var approx = this.integerSqrt(), fix; if (eqv(sqr(approx), this)) { return approx; } - - if (isReal(approx)) { - if (isFinite(toFixnum(this)) && - isFinite(toFixnum(approx))) { - return FloatPoint.makeInstance( - searchIter(toFixnum(this), toFixnum(approx))); + fix = toFixnum(this); + if (isFinite(fix)) { + if (fix >= 0) { + return FloatPoint.makeInstance(Math.sqrt(fix)); } else { - return approx; - } - } else { - if (isFinite(toFixnum(this)) && - isFinite(toFixnum(imaginaryPart(approx)))) { return Complex.makeInstance( - 0, - FloatPoint.makeInstance( - searchIter( - (-toFixnum(this)), - toFixnum(imaginaryPart(approx))))); - } else { - return approx; + 0, + FloatPoint.makeInstance(Math.sqrt(-fix))); } + } else { + return approx; } - } + }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. // // An optional limit on the decimal expansion can be provided, in which // case the search cuts off if we go past the limit. // If this happens, the third argument returned becomes '...' to indicate // that the search was prematurely cut off. var toRepeatingDecimal = (function() { var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { if (limit-- <= 0) { return [digits.join(''), '...'] } var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d, options) { // default limit on decimal expansion; can be overridden var limit = 512; if (options && typeof(options.limit) !== 'undefined') { limit = options.limit; } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })(); diff --git a/test/tests.js b/test/tests.js index 8a44597..45b8654 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1685,1063 +1685,1071 @@ describe('divide', { 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeComplex(makeFloat(.25), makeFloat(0.0)))); assertTrue(eqv(divide(makeComplex(2, 6), makeComplex(4, 1)), makeComplex(makeRational(14, 17), makeRational(22, 17)))); }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { assertTrue(eqv(sqrt(makeBignum("4")), 2)) assertTrue(eqv(sqrt(makeBignum("-4")), makeComplex(0, 2))) assertTrue(diffPercent(makeFloat(4893703081.846022), sqrt(makeBignum("23948329853269253680"))) < 1e-2) + assertTrue(diffPercent(sqrt(expt(15, 21)).toFixnum(), + 2233357359474.6265) + < 2e-10); + assertTrue(eqv(sqrt(expt(15, 22)), + expt(15, 11))); + assertTrue(eqv(sqrt(expt(15, 22)), + expt(15, 11))); }, 'rationals': function() { assertTrue(eqv(sqrt(makeRational(1, 4)), makeRational(1, 2))); assertTrue(eqv(sqrt(makeRational(-1, 4)), makeComplex(0, makeRational(1, 2)))); }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); + }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertFails(function() { floor(makeComplex(nan, negative_zero))} ); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertFails(function() { floor(makeComplex(makeFloat(-1.999), makeFloat(0.0)))}); assertFails(function() { floor(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))) }); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234568), ceiling(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234567), ceiling(makeFloat(-1234567891234567.8))); assertEqv(nan, ceiling(nan)); assertEqv(inf, ceiling(inf)); assertEqv(negative_inf, ceiling(negative_inf)); assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(nan))); assertFails(function() { ceiling(makeComplex(makeFloat(0), nan))}); assertFails(function() { ceiling(makeComplex(nan, makeFloat(1)))}); assertFails(function() { ceiling(makeComplex(makeFloat(1), nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertFails(function() { ceiling(makeComplex(nan, negative_zero))} ); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(makeFloat(0),inf))}); assertFails(function() { ceiling(makeComplex(inf,makeFloat(0)))}); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertFails(function() { ceiling(makeComplex(makeFloat(-1.999), makeFloat(0)))}); assertFails(function() { ceiling(makeComplex(makeFloat(1234567891234567.8), makeFloat(0)))}); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this
dyoo/js-numbers
4926282f436492a272880b9247460c722ecf3da9
biginteger sqrt should behave a little better now
diff --git a/src/js-numbers.js b/src/js-numbers.js index cfe27f7..eec0d97 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3270,776 +3270,811 @@ if (typeof(exports) !== 'undefined') { // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); (function() { - // Get an approximation using integerSqrt, + + + // Classic implementation of Newton-Ralphson square-root search. + // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number + var searchIter = function(n, guess) { + var maxIterations = 100; + while(Math.abs(guess*guess - n) > 0.000001 && + (maxIterations--) > 0) { + guess = (guess + n/guess) / 2 + + } + return guess; + }; + + // Get an approximation using integerSqrt, and then start another + // Newton-Ralphson search if necessary. BigInteger.prototype.sqrt = function() { var approx = this.integerSqrt(); + var f; if (eqv(sqr(approx), this)) { return approx; } - // TODO: get closer to the result by Newton's method if - // we can do so by floating-point - return approx; + + if (isReal(approx)) { + if (isFinite(toFixnum(this)) && + isFinite(toFixnum(approx))) { + return FloatPoint.makeInstance( + searchIter(toFixnum(this), toFixnum(approx))); + } else { + return approx; + } + } else { + if (isFinite(toFixnum(this)) && + isFinite(toFixnum(imaginaryPart(approx)))) { + return Complex.makeInstance( + 0, + FloatPoint.makeInstance( + searchIter( + (-toFixnum(this)), + toFixnum(imaginaryPart(approx))))); + } else { + return approx; + } + } } })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. // // An optional limit on the decimal expansion can be provided, in which // case the search cuts off if we go past the limit. // If this happens, the third argument returned becomes '...' to indicate // that the search was prematurely cut off. var toRepeatingDecimal = (function() { var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { if (limit-- <= 0) { return [digits.join(''), '...'] } var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d, options) { // default limit on decimal expansion; can be overridden var limit = 512; if (options && typeof(options.limit) !== 'undefined') { limit = options.limit; } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })();
dyoo/js-numbers
74ca5ecd5daa1fdf7c36b7c5da642e744097708b
some simplifications
diff --git a/src/js-numbers.js b/src/js-numbers.js index 7520712..cfe27f7 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,850 +1,831 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, - { isYSpecialCase: function(y) { - return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, - onYSpecialCase: function(x, y) { - var pos = (y !== NEGATIVE_ZERO); - - - if (isReal(x)) { - if (isExact(x)) { - if (greaterThan(x, 0)) { - return pos ? inf : neginf; - } else if (lessThan(x, 0)) { - return pos ? neginf : inf; - } else { - return 0; - } - } else { - // both x and y are inexact - if (isNaN(toFixnum(x))) { - return NaN; - } else if (greaterThan(x, 0)) { - return pos ? inf : neginf; - } else if (lessThan(x, 0)) { - return pos ? neginf : inf; - } else { - return NaN; - } - } - } else { - if (x.level < y.level) x = x.liftTo(y); - if (y.level < x.level) y = y.liftTo(x); - return x.divide(y); + { isXSpecialCase: function(x) { + return (eqv(x, 0)); + }, + onXSpecialCase: function(x, y) { + if (eqv(y, 0)) { + throwRuntimeError("/: division by zero", x, y); } + return 0; + }, + isYSpecialCase: function(y) { + return (eqv(y, 0)); }, + onYSpecialCase: function(x, y) { + throwRuntimeError("/: division by zero", x, y); } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (! isInteger(x)) { throwRuntimeError('integer-sqrt: the argument ' + x.toString() + " is not an integer.", x); } if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; @@ -1239,1119 +1220,1073 @@ if (typeof(exports) !== 'undefined') { // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(-0.0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } else if (n === 0) { if ((1/n) === -Infinity) { return NEGATIVE_ZERO; } else { return INEXACT_ZERO; } } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { return FloatPoint.makeInstance(this.n - other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { - if (this.n === 0 || other.n === 0) { - if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { - return INEXACT_ZERO; - } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { - return NEGATIVE_ZERO; - } - return INEXACT_ZERO; - } - - if (this.isFinite() && other.isFinite()) { - var product = this.n * other.n; - if (product !== 0) { - return FloatPoint.makeInstance(product); - } - return sign(this) * sign(other) == 1 ? - FloatPoint.makeInstance(0) : NEGATIVE_ZERO; - } else if (isNaN(this.n) || isNaN(other.n)) { - return NaN; - } else { - return ((sign(this) * sign(other) === 1) ? inf : neginf); - } + return FloatPoint.makeInstance(this.n * other.n); }; FloatPoint.prototype.divide = function(other) { - if (this.isFinite() && other.isFinite()) { - if (other.n === 0) { - return throwRuntimeError("/: division by zero", this, other); - } - return FloatPoint.makeInstance(this.n / other.n); - } else if (isNaN(this.n) || isNaN(other.n)) { - return NaN; - } else if (! this.isFinite() && !other.isFinite()) { - return NaN; - } else if (this.isFinite() && !other.isFinite()) { - return FloatPoint.makeInstance(0.0); - } else if (! this.isFinite() && other.isFinite()) { - return ((sign(this) * sign(other) === 1) ? inf : neginf); - } else { - return throwRuntimeError("impossible", this, other); - } + return FloatPoint.makeInstance(this.n / other.n); }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { - if (! isFinite(this.n)) { - return this; - } else if (this === NEGATIVE_ZERO) { - return this; - } else { - return FloatPoint.makeInstance(Math.floor(this.n)); - } + return FloatPoint.makeInstance(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { - if (! isFinite(this.n)) { - return this; - } else if (this === NEGATIVE_ZERO) { - return this; - } return FloatPoint.makeInstance(Math.ceil(this.n)); + return FloatPoint.makeInstance(Math.ceil(this.n)); }; - FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } if (this.isInexact() || other.isInexact()) { // http://portal.acm.org/citation.cfm?id=1039814 // We currently use Smith's method, though we should // probably switch over to Priest's method. a = this.r; b = this.i; c = other.r; d = other.i; if (lessThanOrEqual(abs(d), abs(c))) { r = divide(d, c); x = divide(add(a, multiply(b, r)), add(c, multiply(d, r))); y = divide(subtract(b, multiply(a, r)), add(c, multiply(d, r))); } else { r = divide(c, d); x = divide(add(multiply(a, r), b), add(multiply(c, r), d)); y = divide(subtract(multiply(b, r), a), add(multiply(c, r), d)); } return Complex.makeInstance(x, y); } else { var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = diff --git a/test/tests.js b/test/tests.js index 1edb2ba..8a44597 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,578 +1,580 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertEqv = function(x, y) { value_of(eqv(x, y)).should_be_true(); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); + value_of(toFixnum(makeRational(1, 5)) === 0.2) + .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { assertTrue(eqv(makeComplexPolar(1, 2), makeComplex(makeFloat(-0.4161468365471424), makeFloat(0.9092974268256817)))); }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); @@ -996,1025 +998,1035 @@ describe('toExact', { assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); assertTrue(eqv(toExact(makeComplex(0, 1)), makeComplex(0, 1))); assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(-1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(1.1234))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(234), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(200), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(34), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(-24), makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(24), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(toFixnum(makeRational(16, 17))), makeFloat(1.1234)), subtract(1, makeComplex(makeFloat(toFixnum(makeRational(1, 17))), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, + 'floating / floating' : function() { + assertTrue(eqv(subtract(makeFloat(1.2), makeFloat(0.2)), + makeFloat(1.2-0.2))); + + assertTrue(eqv(subtract(nan, nan), + nan)); + assertTrue(eqv(subtract(nan, makeFloat(3.0)), + nan)); + assertTrue(eqv(subtract(nan, makeFloat(-3.0)), + nan)); // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, 0))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(negative_zero, multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(0, 0), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeComplex(makeFloat(.25), makeFloat(0.0)))); assertTrue(eqv(divide(makeComplex(2, 6), makeComplex(4, 1)), makeComplex(makeRational(14, 17), makeRational(22, 17)))); }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))));
dyoo/js-numbers
b133bf5476ac67477d77ce6b4bcf5905ae8db974
simplifying some of the logic
diff --git a/src/js-numbers.js b/src/js-numbers.js index d8a0539..7520712 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1200,1076 +1200,1059 @@ if (typeof(exports) !== 'undefined') { // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(-0.0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } else if (n === 0) { if ((1/n) === -Infinity) { return NEGATIVE_ZERO; } else { return INEXACT_ZERO; } } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { - if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { - return NEGATIVE_ZERO; - } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { - var result = this.n - other.n; - if (result === 0.0) { - if (other === NEGATIVE_ZERO) { - return FloatPoint.makeInstance(result); - } - else if (this === NEGATIVE_ZERO) { - return NEGATIVE_ZERO; - } - } - return FloatPoint.makeInstance(result); + return FloatPoint.makeInstance(this.n - other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { - if (this === NEGATIVE_ZERO) { - return FloatPoint.makeInstance(0); - } else if (this.n === 0) { - return NEGATIVE_ZERO; - } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return INEXACT_ZERO; } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return INEXACT_ZERO; } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } if (this.isInexact() || other.isInexact()) { // http://portal.acm.org/citation.cfm?id=1039814 // We currently use Smith's method, though we should // probably switch over to Priest's method. a = this.r; b = this.i; c = other.r; d = other.i; if (lessThanOrEqual(abs(d), abs(c))) { r = divide(d, c); x = divide(add(a, multiply(b, r)), add(c, multiply(d, r))); y = divide(subtract(b, multiply(a, r)), add(c, multiply(d, r))); } else { r = divide(c, d); x = divide(add(multiply(a, r), b), add(multiply(c, r), d)); y = divide(subtract(multiply(b, r), a), add(multiply(c, r), d)); } return Complex.makeInstance(x, y); } else { var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; };
dyoo/js-numbers
2c6ddbff9e31db6bebacaf8aaa284f2f4adabb1d
added test for negative zero. I need to simplify all the floatpoint stuff now that I know how to test for negative zero. How embarrassing... :)
diff --git a/src/js-numbers.js b/src/js-numbers.js index c8f9480..d8a0539 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1065,1040 +1065,1046 @@ if (typeof(exports) !== 'undefined') { function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. - var NEGATIVE_ZERO = new FloatPoint(0); + var NEGATIVE_ZERO = new FloatPoint(-0.0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; + } else if (n === 0) { + if ((1/n) === -Infinity) { + return NEGATIVE_ZERO; + } else { + return INEXACT_ZERO; + } } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return INEXACT_ZERO; } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return INEXACT_ZERO; } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); };
dyoo/js-numbers
986cf3eff4871d2a2587e8470ab9bb1e3902bcfa
fixing typo
diff --git a/src/js-numbers.js b/src/js-numbers.js index ac9252f..c8f9480 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1694,1025 +1694,1025 @@ if (typeof(exports) !== 'undefined') { } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return INEXACT_ZERO; } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return INEXACT_ZERO; } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); } else { return Complex.makeInstance( INEXACT_ZERO, FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } if (this.isInexact() || other.isInexact()) { // http://portal.acm.org/citation.cfm?id=1039814 // We currently use Smith's method, though we should // probably switch over to Priest's method. a = this.r; b = this.i; c = other.r; d = other.i; if (lessThanOrEqual(abs(d), abs(c))) { r = divide(d, c); x = divide(add(a, multiply(b, r)), add(c, multiply(d, r))); y = divide(subtract(b, multiply(a, r)), add(c, multiply(d, r))); } else { r = divide(c, d); x = divide(add(multiply(a, r), b), add(multiply(c, r), d)); y = divide(subtract(multiply(b, r), a), add(multiply(c, r), d)); } - return makeComplex(x, y); + return Complex.makeInstance(x, y); } else { var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(digitRegexp) && (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1;
dyoo/js-numbers
4d2f4d1205fa2118200d1248e40655867dfc70e8
fixing expansion of toRepeatedDecimal
diff --git a/README b/README index f5bd228..e9c9449 100644 --- a/README +++ b/README @@ -1,306 +1,310 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a toplevel namespace called jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInexact: scheme-number -> boolean Produces true if the number is inexact. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. toInexact: scheme-number -> scheme-number Converts the number to an inexact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. quotient: scheme-number scheme-number -> scheme-number Produces the quotient. Both inputs must be integers. remainder: scheme-number scheme-number -> scheme-number Produces the remainder. Both inputs must be integers. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. +toRepeatedDecimal: scheme-number scheme-number {limit: number}? -> [string, string, string] + Produces a string representation of the decimal expansion; the first and second + argument must be integers. Returns an array of three parts: the portion before + the decimal, the non-repeating part, and then the repeating part. - - + If the expansion goes beyond the limit (by default, 256 characters), then + the expansion will be cut off, and the third portion will be '...'. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, sgn * Bring over the numeric test cases from Moby. * Add real documentation. ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. June 2010: got implementation of integer-sqrt from Ugur Cekmez; brought in some fixes from Ethan Cecchetti. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index f5a34f2..ac9252f 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3432,676 +3432,690 @@ if (typeof(exports) !== 'undefined') { else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); (function() { // Get an approximation using integerSqrt, BigInteger.prototype.sqrt = function() { var approx = this.integerSqrt(); if (eqv(sqr(approx), this)) { return approx; } // TODO: get closer to the result by Newton's method if // we can do so by floating-point return approx; } })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// - // toRepeatingDecimal: jsnum jsnum -> [string, string, string] + // toRepeatingDecimal: jsnum jsnum {limit: number}? -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. + // + // An optional limit on the decimal expansion can be provided, in which + // case the search cuts off if we go past the limit. + // If this happens, the third argument returned becomes '...' to indicate + // that the search was prematurely cut off. var toRepeatingDecimal = (function() { - var getResidue = function(r, d) { + var getResidue = function(r, d, limit) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { + if (limit-- <= 0) { + return [digits.join(''), '...'] + } + var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; - return function(n, d) { + return function(n, d, options) { + // default limit on decimal expansion; can be overridden + var limit = 512; + if (options && typeof(options.limit) !== 'undefined') { + limit = options.limit; + } if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); - var afterDecimals = getResidue(remainder(n, d), d); + var afterDecimals = getResidue(remainder(n, d), d, limit); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })(); diff --git a/test/tests.js b/test/tests.js index 1724d64..1edb2ba 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2723,1025 +2723,1052 @@ describe('asin', { } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); assertTrue(eqv(integerSqrt(negative_zero), negative_zero)); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('repeating decimals', { tests: function() { assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); + }, + + limitRendering: function() { + var OPTIONS = {limit: 5}; + assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1, OPTIONS)); + assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2, OPTIONS)); + assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3, OPTIONS)); + assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4, OPTIONS)); + assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5, OPTIONS)); + assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6, OPTIONS)); + assertEquals(['0', '05882', '...'], + toRepeatingDecimal(1, 17, {limit : 5})); + + assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8, {limit : 4})); + assertEquals(['0', '125', '...'], toRepeatingDecimal(1, 8, {limit : 3})); + assertEquals(['0', '12', '...'], toRepeatingDecimal(1, 8, {limit : 2})); + assertEquals(['0', '1', '...'], toRepeatingDecimal(1, 8, {limit : 1})); + assertEquals(['0', '', '...'], toRepeatingDecimal(1, 8, {limit : 0})); + + assertEquals(['10012718086', + '8577149703838870007766167', + '...'], + toRepeatingDecimal(makeBignum("239872983562893234879"), + makeBignum("23956829852"), + {limit:25})); + } + }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertEqv(divide(makeFloat(1),makeFloat(0)), inf); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(diffPercent(realPart(asin(makeComplex(1, 5))), makeFloat(0.1937931365549321)) < 1e-2); assertTrue(diffPercent(imaginaryPart(asin(makeComplex(1, 5))), makeFloat(2.3309746530493123)) < 1e-2); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false));
dyoo/js-numbers
ef7a31805cb4a5cd695af7eca425431442711e62
repairing the test case for asin
diff --git a/test/tests.js b/test/tests.js index 37ff826..1724d64 100644 --- a/test/tests.js +++ b/test/tests.js @@ -3018,854 +3018,857 @@ describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); assertTrue(eqv(integerSqrt(negative_zero), negative_zero)); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('repeating decimals', { tests: function() { assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertEqv(divide(makeFloat(1),makeFloat(0)), inf); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); - assertTrue(equals(asin(1), - divide(pi, 2))); - assertTrue(equals(asin(makeRational(1, 4)), - makeFloat(0.25268025514207865))); - assertTrue(equals(asin(makeComplex(1, 5)), - makeComplex(makeFloat(0.1937931365549321), - makeFloat(2.3309746530493123)))); + assertTrue(equals(asin(1), + divide(pi, 2))); + assertTrue(equals(asin(makeRational(1, 4)), + makeFloat(0.25268025514207865))); + assertTrue(diffPercent(realPart(asin(makeComplex(1, 5))), + makeFloat(0.1937931365549321)) + < 1e-2); + assertTrue(diffPercent(imaginaryPart(asin(makeComplex(1, 5))), + makeFloat(2.3309746530493123)) + < 1e-2); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); assertEquals("5.0+0.0i", (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", (makeComplex(5, 1)).toString()); assertEquals("4-2i", (makeComplex(4, -2)).toString()); }, testQuotient : function(){ assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(36), makeRational(7)), makeRational(5))); assertTrue(eqv(1, quotient(7, 5))); }, testRemainder : function(){ assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, modulo(n1, n2)); assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(isReal(pi)); assertTrue(isReal(1)); assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!isReal("hi")); }, testRound : function(){ assertTrue(equals(round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(round(makeRational(3)), makeRational(3))); assertTrue(equals(round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(round(makeRational(-17, 4)), makeRational(-4))); }, // testSgn : function(){ // assertTrue(equals(sgn(makeFloat(4)), 1)); // assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); // assertTrue(equals(sgn(0), 0)); // }, // testZero_question_ : function(){ // assertTrue(Kernel.zero_question_(0)); // assertTrue(!Kernel.zero_question_(1)); // assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); // } });
dyoo/js-numbers
5b15b1d412d25e52ca27d5341694994c19603a0c
fixing FloatPoint.prototype.integerSqrt
diff --git a/src/js-numbers.js b/src/js-numbers.js index c84a860..f5a34f2 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -175,1033 +175,1036 @@ if (typeof(exports) !== 'undefined') { n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { var pos = (y !== NEGATIVE_ZERO); if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return 0; } } else { // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { + if (! isInteger(x)) { + throwRuntimeError('integer-sqrt: the argument ' + x.toString() + + " is not an integer.", x); + } if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } - return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. @@ -1360,1032 +1363,1033 @@ if (typeof(exports) !== 'undefined') { // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return INEXACT_ZERO; } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return INEXACT_ZERO; } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { + if (this === NEGATIVE_ZERO) { return this; } if (isInteger(this)) { if(this.n >= 0) { - return FloatPoint.makeInstance(floor(sqrt(this.n))); - }else { - return Complex.makeInstance(0, - FloatPoint.makeInstance(floor(sqrt(-this.n)))) + return FloatPoint.makeInstance(Math.floor(Math.sqrt(this.n))); + } else { + return Complex.makeInstance( + INEXACT_ZERO, + FloatPoint.makeInstance(Math.floor(Math.sqrt(-this.n)))); } - } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } if (this.isInexact() || other.isInexact()) { // http://portal.acm.org/citation.cfm?id=1039814 // We currently use Smith's method, though we should // probably switch over to Priest's method. a = this.r; b = this.i; c = other.r; d = other.i; if (lessThanOrEqual(abs(d), abs(c))) { r = divide(d, c); x = divide(add(a, multiply(b, r)), add(c, multiply(d, r))); y = divide(subtract(b, multiply(a, r)), add(c, multiply(d, r))); } else { r = divide(c, d); x = divide(add(multiply(a, r), b), add(multiply(c, r), d)); y = divide(subtract(multiply(b, r), a), add(multiply(c, r), d)); } return makeComplex(x, y); } else { var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ diff --git a/test/tests.js b/test/tests.js index de87ade..37ff826 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2560,1056 +2560,1057 @@ describe('magnitude', { }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); - + assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); - assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); - assertTrue(eqv(makeFloat(1.0), + assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), - integerSqrt(makeFloat(12345.0)))); + integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), - integerSqrt(makeFloat(-12345.0)))); + integerSqrt(makeFloat(-12345.0)))); + assertTrue(eqv(integerSqrt(negative_zero), + negative_zero)); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('repeating decimals', { tests: function() { assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertEqv(divide(makeFloat(1),makeFloat(0)), inf); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){
dyoo/js-numbers
cf1ad136ed0558f9cd43873c9ddab210be1ed2b2
repairing the test cases on ceiling
diff --git a/test/tests.js b/test/tests.js index 97a952e..de87ade 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1978,1069 +1978,1068 @@ describe('expt', { assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { assertTrue(eqv(sqrt(makeBignum("4")), 2)) assertTrue(eqv(sqrt(makeBignum("-4")), makeComplex(0, 2))) assertTrue(diffPercent(makeFloat(4893703081.846022), sqrt(makeBignum("23948329853269253680"))) < 1e-2) }, 'rationals': function() { assertTrue(eqv(sqrt(makeRational(1, 4)), makeRational(1, 2))); assertTrue(eqv(sqrt(makeRational(-1, 4)), makeComplex(0, makeRational(1, 2)))); }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertFails(function() { floor(makeComplex(nan, negative_zero))} ); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertFails(function() { floor(makeComplex(makeFloat(-1.999), makeFloat(0.0)))}); assertFails(function() { floor(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))) }); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234568), ceiling(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234567), ceiling(makeFloat(-1234567891234567.8))); assertEqv(nan, ceiling(nan)); assertEqv(inf, ceiling(inf)); assertEqv(negative_inf, ceiling(negative_inf)); assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { - assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); - assertFails(function() { ceiling(makeComplex(0, nan))}); - assertFails(function() { ceiling(makeComplex(nan, 1))}); - assertFails(function() { ceiling(makeComplex(1, nan))}); - assertFails(function() { ceiling(makeComplex(nan, inf))}); - assertFails(function() { ceiling(makeComplex(inf, nan))}); - assertEquals(nan,floor(makeComplex(nan, negative_zero))); + assertTrue(eqv(nan, ceiling(nan))); + assertFails(function() { ceiling(makeComplex(makeFloat(0), nan))}); + assertFails(function() { ceiling(makeComplex(nan, makeFloat(1)))}); + assertFails(function() { ceiling(makeComplex(makeFloat(1), nan))}); + assertFails(function() { ceiling(makeComplex(nan, inf))}); + assertFails(function() { ceiling(makeComplex(inf, nan))}); + assertFails(function() { ceiling(makeComplex(nan, negative_zero))} ); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); - assertFails(function() { ceiling(makeComplex(0,inf))}); - assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); + assertFails(function() { ceiling(makeComplex(makeFloat(0),inf))}); + assertFails(function() { ceiling(makeComplex(inf,makeFloat(0)))}); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, - ceiling(makeComplex(makeRational(makeBignum("9919"), - makeBignum("9")), - 0)))); + ceiling(makeComplex(makeRational(makeBignum("9919"), + makeBignum("9")), + 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), - makeBignum("0"))))); + makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), - makeBignum("0"))))); + makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), - makeBignum("0"))))); + makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), - makeBignum("0"))))); + makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), - makeBignum("2")), - makeBignum("0"))))); + makeBignum("2")), + makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); - assertTrue(eqv(makeFloat(-1), ceiling(makeComplex(makeFloat(-1.999), - makeFloat(0))))); - assertTrue(eqv(makeFloat(1234567891234568), - ceiling(makeComplex(makeFloat(1234567891234567.8), - makeFloat(0))))); + assertFails(function() { ceiling(makeComplex(makeFloat(-1.999), + makeFloat(0)))}); + assertFails(function() { ceiling(makeComplex(makeFloat(1234567891234567.8), + makeFloat(0)))}); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7"))));
dyoo/js-numbers
4c844e9552fc6a36594e9eccfb879f86f0873b6d
repairing floor test cases
diff --git a/test/tests.js b/test/tests.js index 020e314..97a952e 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1842,1068 +1842,1067 @@ describe('lessThanOrEqual', { 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { assertTrue(eqv(sqrt(makeBignum("4")), 2)) assertTrue(eqv(sqrt(makeBignum("-4")), makeComplex(0, 2))) assertTrue(diffPercent(makeFloat(4893703081.846022), sqrt(makeBignum("23948329853269253680"))) < 1e-2) }, 'rationals': function() { assertTrue(eqv(sqrt(makeRational(1, 4)), makeRational(1, 2))); assertTrue(eqv(sqrt(makeRational(-1, 4)), makeComplex(0, makeRational(1, 2)))); }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); - assertFails(function() { floor(makeComplex(0, nan))}); - assertFails(function() { floor(makeComplex(nan, 1))}); - assertFails(function() { floor(makeComplex(1, nan))}); - assertFails(function() { floor(makeComplex(nan, inf))}); - assertFails(function() { floor(makeComplex(inf, nan))}); + assertFails(function() { floor(makeComplex(0, nan))}); + assertFails(function() { floor(makeComplex(nan, 1))}); + assertFails(function() { floor(makeComplex(1, nan))}); + assertFails(function() { floor(makeComplex(nan, inf))}); + assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); - assertEquals(nan,floor(makeComplex(nan, negative_zero))); - assertFails(function() { floor(makeComplex(inf,inf))}); - assertFails(function() { floor(makeComplex(0,inf))}); - assertTrue(eqv(inf, floor(makeComplex(inf,0)))); + assertFails(function() { floor(makeComplex(nan, negative_zero))} ); + assertFails(function() { floor(makeComplex(inf,inf))}); + assertFails(function() { floor(makeComplex(0,inf))}); + assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, - floor(makeComplex(makeRational(makeBignum("9919"), - makeBignum("9")), - 0)))); + floor(makeComplex(makeRational(makeBignum("9919"), + makeBignum("9")), + 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), - floor(makeComplex( - makeRational(makeBignum("100000000000000000000"), - makeBignum("200000000000000000000")), - makeBignum("0"))))); - assertTrue(eqv(makeFloat(-2), floor(makeComplex(makeFloat(-1.999), - makeFloat(0.0))))); - assertTrue(eqv(makeFloat(1234567891234567), - floor(makeComplex(makeFloat(1234567891234567.8), - makeFloat(0))))); + floor(makeComplex( + makeRational(makeBignum("100000000000000000000"), + makeBignum("200000000000000000000")), + makeBignum("0"))))); + assertFails(function() { floor(makeComplex(makeFloat(-1.999), + makeFloat(0.0)))}); + assertFails(function() { floor(makeComplex(makeFloat(1234567891234567.8), + makeFloat(0))) }); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234568), ceiling(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234567), ceiling(makeFloat(-1234567891234567.8))); assertEqv(nan, ceiling(nan)); assertEqv(inf, ceiling(inf)); assertEqv(negative_inf, ceiling(negative_inf)); assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-1), ceiling(makeComplex(makeFloat(-1.999), makeFloat(0))))); assertTrue(eqv(makeFloat(1234567891234568), ceiling(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } });
dyoo/js-numbers
ce68f8f6bf8f7d2b8f60d666b1cc7337379efca3
repairing inexact complex division so it uses Smith's method to avoid overflow.
diff --git a/src/js-numbers.js b/src/js-numbers.js index dde6d52..c84a860 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1656,1050 +1656,1077 @@ if (typeof(exports) !== 'undefined') { if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return INEXACT_ZERO; } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return INEXACT_ZERO; } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; + + + + Complex.prototype.divide = function(other){ + var a, b, c, d, r, x, y; // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } + if (this.isInexact() || other.isInexact()) { + // http://portal.acm.org/citation.cfm?id=1039814 + // We currently use Smith's method, though we should + // probably switch over to Priest's method. + a = this.r; + b = this.i; + c = other.r; + d = other.i; + if (lessThanOrEqual(abs(d), abs(c))) { + r = divide(d, c); + x = divide(add(a, multiply(b, r)), + add(c, multiply(d, r))); + y = divide(subtract(b, multiply(a, r)), + add(c, multiply(d, r))); + } else { + r = divide(c, d); + x = divide(add(multiply(a, r), b), + add(multiply(c, r), d)); + y = divide(subtract(multiply(b, r), a), + add(multiply(c, r), d)); + } + return makeComplex(x, y); + } else { + var con = conjugate(other); + var up = multiply(this, con); - var con = conjugate(other); - var up = multiply(this, con); - - // Down is guaranteed to be real by this point. - var down = realPart(multiply(other, con)); + // Down is guaranteed to be real by this point. + var down = realPart(multiply(other, con)); - var result = Complex.makeInstance( - divide(realPart(up), down), - divide(imaginaryPart(up), down)); - return result; + var result = Complex.makeInstance( + divide(realPart(up), down), + divide(imaginaryPart(up), down)); + return result; + } }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, - subtract(0, - this.i)); + subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(digitRegexp) && (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; diff --git a/test/tests.js b/test/tests.js index 83ff01e..020e314 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,602 +1,604 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertEqv = function(x, y) { value_of(eqv(x, y)).should_be_true(); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { - // FIXME: add tests for polar construction + assertTrue(eqv(makeComplexPolar(1, 2), + makeComplex(makeFloat(-0.4161468365471424), + makeFloat(0.9092974268256817)))); }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { // If any component of a complex is inexact, both // the real and imaginary parts get turned into // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); @@ -1205,1026 +1207,1030 @@ describe('add', { assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(-1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(1.1234))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(234), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(200), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(34), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(-24), makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(24), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(toFixnum(makeRational(16, 17))), makeFloat(1.1234)), subtract(1, makeComplex(makeFloat(toFixnum(makeRational(1, 17))), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, 0))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(negative_zero, multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(0, 0), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), - makeFloat(.25))) - // FIXME: we're missing this + makeComplex(makeFloat(.25), makeFloat(0.0)))); + assertTrue(eqv(divide(makeComplex(2, 6), + makeComplex(4, 1)), + makeComplex(makeRational(14, 17), + makeRational(22, 17)))); + }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { assertTrue(eqv(sqrt(makeBignum("4")), 2)) assertTrue(eqv(sqrt(makeBignum("-4")), makeComplex(0, 2))) assertTrue(diffPercent(makeFloat(4893703081.846022), sqrt(makeBignum("23948329853269253680"))) < 1e-2) }, 'rationals': function() { assertTrue(eqv(sqrt(makeRational(1, 4)), makeRational(1, 2))); assertTrue(eqv(sqrt(makeRational(-1, 4)), makeComplex(0, makeRational(1, 2)))); }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); },
dyoo/js-numbers
87d64fcedd330f3018fdf4b2e0b0b6bf041df74c
fixing the implementation of FloatPoint.proottype.multiply with regard to negative zero
diff --git a/src/js-numbers.js b/src/js-numbers.js index 27fa91a..dde6d52 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1247,1025 +1247,1032 @@ if (typeof(exports) !== 'undefined') { var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { - if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } + if (this.n === 0 || other.n === 0) { + if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { + return INEXACT_ZERO; + } else if (this === NEGATIVE_ZERO || other === NEGATIVE_ZERO) { + return NEGATIVE_ZERO; + } + return INEXACT_ZERO; + } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), diff --git a/test/tests.js b/test/tests.js index ab1e4a4..83ff01e 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1102,1034 +1102,1034 @@ describe('add', { }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(-1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(1.1234))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(234), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(200), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(34), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(-24), makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(24), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(toFixnum(makeRational(16, 17))), makeFloat(1.1234)), subtract(1, makeComplex(makeFloat(toFixnum(makeRational(1, 17))), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, 0))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); - assertTrue(eqv(makeFloat(0), - multiply(makeFloat(0), negative_zero))); - assertTrue(eqv(negative_zero, - multiply(negative_zero, makeFloat(0)))); - assertTrue(eqv(makeComplex(negative_zero, negative_zero), - multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); - assertTrue(eqv(makeComplex(negative_zero, negative_zero), - multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); - assertTrue(eqv(makeComplex(negative_zero, negative_zero), - multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); + assertTrue(eqv(negative_zero, + multiply(makeFloat(0), negative_zero))); + assertTrue(eqv(negative_zero, + multiply(negative_zero, makeFloat(0)))); + assertTrue(eqv(makeComplex(0, 0), + multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); + assertTrue(eqv(makeComplex(negative_zero, negative_zero), + multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); + assertTrue(eqv(makeComplex(negative_zero, negative_zero), + multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this }
dyoo/js-numbers
46fc2190cd62661ec000cb6ef7ca275ead0bd195
fixing bug in FloatPoint.prototype.subtract: it wasn't comparing NEGATIVE_ZERO properly.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 62b8b93..27fa91a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1213,1048 +1213,1048 @@ if (typeof(exports) !== 'undefined') { // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { - if (other.n === NEGATIVE_ZERO) { + if (other === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } - else if (this.n === NEGATIVE_ZERO) { + else if (this === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } - }; + FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; diff --git a/test/tests.js b/test/tests.js index 458bacb..ab1e4a4 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1001,1031 +1001,1032 @@ describe('toExact', { describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(-1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(1.1234))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(234), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(0), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(200), makeFloat(1.1234)), subtract(234, makeComplex(makeFloat(34), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(-24), makeFloat(1.1234)), subtract(0, makeComplex(makeFloat(24), makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeFloat(toFixnum(makeRational(16, 17))), makeFloat(1.1234)), subtract(1, makeComplex(makeFloat(toFixnum(makeRational(1, 17))), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); - assertTrue(eqv(makeFloat(0.0), - subtract(makeFloat(0), negative_zero))); - assertTrue(eqv(negative_zero, - subtract(negative_zero, makeFloat(0)))); - - assertTrue(eqv(makeComplex(negative_zero, negative_zero), - subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); + assertTrue(eqv(makeFloat(0.0), + subtract(makeFloat(0), negative_zero))); + assertTrue(eqv(negative_zero, + subtract(negative_zero, 0))); + assertTrue(eqv(negative_zero, + subtract(negative_zero, makeFloat(0)))); + assertTrue(eqv(makeComplex(negative_zero, negative_zero), + subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this
dyoo/js-numbers
2d1fd44be017bdbe8c92992bc4edd8e86aa25db5
repairing damage to the subtraction test case
diff --git a/test/tests.js b/test/tests.js index 1078fd3..458bacb 100644 --- a/test/tests.js +++ b/test/tests.js @@ -962,1039 +962,1038 @@ describe('toExact', { 'rationals': function() { assertEquals(makeRational(1, 2), toExact(makeRational(1, 2))); assertEquals(makeRational(1, 9999), toExact(makeRational(1, 9999))); assertEquals(makeRational(0, 1), toExact(makeRational(0, 9999))); assertEquals(makeRational(-290, 1), toExact(makeRational(-290, 1))); }, 'floats': function() { assertEquals(makeRational(1, 2), toExact(makeFloat(0.5))); assertEquals(makeRational(1, 10), toExact(makeFloat(0.1))); assertEquals(makeRational(9, 10), toExact(makeFloat(0.9))); assertTrue(isExact(toExact(makeFloat(10234.7)))); assertTrue(diffPercent(makeRational(102347, 10), toExact(makeFloat(10234.7))) < 1); assertEquals(-1, toExact(makeFloat(-1))); assertEquals(0, toExact(makeFloat(0))); assertEquals(1024, toExact(makeFloat(1024))); assertFails(function() { toExact(nan); }); assertFails(function() { toExact(inf); }); assertFails(function() { toExact(negative_inf); }); }, 'complex': function() { assertEquals(0, toExact(makeComplex(0, 0))); assertEquals(99, toExact(makeComplex(99, 0))); assertEquals(makeRational(-1, 2), toExact(makeComplex(makeRational(-1, 2), 0))); assertEquals(makeRational(1, 4), toExact(makeComplex(makeFloat(.25), 0))); assertFails(function() { toExact(makeComplex(nan, 0)); }); assertFails(function() { toExact(makeComplex(inf, 0)); }); assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); assertTrue(eqv(toExact(makeComplex(0, 1)), makeComplex(0, 1))); assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); - assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), - subtract(0, makeComplex(0, makeFloat(1.1234))))); - assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), - subtract(0, makeComplex(0, makeFloat(-1.1234))))); - assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), - subtract(234, makeComplex(0, makeFloat(-1.1234))))); - assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), - subtract(234, makeComplex(34, makeFloat(-1.1234))))); - assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), - subtract(0, makeComplex(24, makeFloat(-1.1234))))); - - assertTrue(eqv(makeComplex(makeRational(16, 17), - makeFloat(1.1234)), - subtract(1, makeComplex(makeRational(1, 17), - makeFloat(-1.1234))))); + assertTrue(eqv(makeComplex(negative_zero, makeFloat(-1.1234)), + subtract(0, makeComplex(makeFloat(0), makeFloat(1.1234))))); + assertTrue(eqv(makeComplex(negative_zero, makeFloat(1.1234)), + subtract(0, makeComplex(makeFloat(0), makeFloat(-1.1234))))); + assertTrue(eqv(makeComplex(makeFloat(234), makeFloat(1.1234)), + subtract(234, makeComplex(makeFloat(0), makeFloat(-1.1234))))); + assertTrue(eqv(makeComplex(makeFloat(200), makeFloat(1.1234)), + subtract(234, makeComplex(makeFloat(34), makeFloat(-1.1234))))); + assertTrue(eqv(makeComplex(makeFloat(-24), makeFloat(1.1234)), + subtract(0, makeComplex(makeFloat(24), makeFloat(-1.1234))))); + assertTrue(eqv(makeComplex(makeFloat(toFixnum(makeRational(16, 17))), + makeFloat(1.1234)), + subtract(1, makeComplex(makeFloat(toFixnum(makeRational(1, 17))), + makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2));
dyoo/js-numbers
885a587d944af9a7753d1bdef8685cd44373bc70
adding initial implementation that just reuses integersqrt
diff --git a/src/js-numbers.js b/src/js-numbers.js index 53737c3..62b8b93 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -3279,776 +3279,791 @@ if (typeof(exports) !== 'undefined') { // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { - guess = average(guess, floor(divide(n, guess))); + guess = average(guess, + floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); + (function() { + // Get an approximation using integerSqrt, + BigInteger.prototype.sqrt = function() { + var approx = this.integerSqrt(); + if (eqv(sqr(approx), this)) { + return approx; + } + // TODO: get closer to the result by Newton's method if + // we can do so by floating-point + return approx; + } + })(); + + // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. var toRepeatingDecimal = (function() { var getResidue = function(r, d) { var digits = []; var seenRemainders = {}; seenRemainders[r] = true; while(true) { var nextDigit = quotient( multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; r = nextRemainder; } } var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( multiply(r, 10), d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d) { if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } var sign = (lessThan(n, 0) ? "-" : ""); n = abs(n); var beforeDecimalPoint = sign + quotient(n, d); var afterDecimals = getResidue(remainder(n, d), d); return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })(); diff --git a/test/tests.js b/test/tests.js index 027762b..1078fd3 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1670,1025 +1670,1029 @@ describe('divide', { }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { assertTrue(eqv(sqrt(makeBignum("4")), 2)) assertTrue(eqv(sqrt(makeBignum("-4")), makeComplex(0, 2))) assertTrue(diffPercent(makeFloat(4893703081.846022), sqrt(makeBignum("23948329853269253680"))) < 1e-2) }, 'rationals': function() { - // FIXME: we're missing this + assertTrue(eqv(sqrt(makeRational(1, 4)), + makeRational(1, 2))); + + assertTrue(eqv(sqrt(makeRational(-1, 4)), + makeComplex(0, makeRational(1, 2)))); }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-2), floor(makeComplex(makeFloat(-1.999), makeFloat(0.0))))); assertTrue(eqv(makeFloat(1234567891234567), floor(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234568), ceiling(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234567), ceiling(makeFloat(-1234567891234567.8))); assertEqv(nan, ceiling(nan)); assertEqv(inf, ceiling(inf)); assertEqv(negative_inf, ceiling(negative_inf)); assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-1), ceiling(makeComplex(makeFloat(-1.999), makeFloat(0))))); assertTrue(eqv(makeFloat(1234567891234568), ceiling(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() {
dyoo/js-numbers
ac4bf0acbc918cb6c04bd54210ed0b58e398a55a
adding missing test for sqrt of bignums
diff --git a/test/tests.js b/test/tests.js index 934237c..027762b 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1658,1025 +1658,1033 @@ describe('multiply', { describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { - // FIXME: we're missing this + assertTrue(eqv(sqrt(makeBignum("4")), + 2)) + + assertTrue(eqv(sqrt(makeBignum("-4")), + makeComplex(0, 2))) + + assertTrue(diffPercent(makeFloat(4893703081.846022), + sqrt(makeBignum("23948329853269253680"))) + < 1e-2) }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-2), floor(makeComplex(makeFloat(-1.999), makeFloat(0.0))))); assertTrue(eqv(makeFloat(1234567891234567), floor(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234568), ceiling(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234567), ceiling(makeFloat(-1234567891234567.8))); assertEqv(nan, ceiling(nan)); assertEqv(inf, ceiling(inf)); assertEqv(negative_inf, ceiling(negative_inf)); assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-1), ceiling(makeComplex(makeFloat(-1.999), makeFloat(0))))); assertTrue(eqv(makeFloat(1234567891234568), ceiling(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this },
dyoo/js-numbers
c09f7e831fd174b63a12551e33794571828af8c3
(sin 0) == 0
diff --git a/src/js-numbers.js b/src/js-numbers.js index b7e7b2a..53737c3 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -117,1024 +117,1025 @@ if (typeof(exports) !== 'undefined') { // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { var pos = (y !== NEGATIVE_ZERO); if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return 0; } } else { // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { + if (eqv(n, 0)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { if (eqv(x, 0)) { return FloatPoint.makeInstance(1.0); } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real.
dyoo/js-numbers
5df8f8d1781588fc0f845137f2038437494b2dc3
cosh on 0 === 1.0
diff --git a/src/js-numbers.js b/src/js-numbers.js index 494ad33..b7e7b2a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -261,1024 +261,1027 @@ if (typeof(exports) !== 'undefined') { }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { var pos = (y !== NEGATIVE_ZERO); if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return 0; } } else { // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { + if (eqv(x, 0)) { + return FloatPoint.makeInstance(1.0); + } return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d);
dyoo/js-numbers
fa89d8a78556a35891188b79d1645f64ec4dd02c
exactness of cos on 0
diff --git a/src/js-numbers.js b/src/js-numbers.js index 9c9e13e..494ad33 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -108,1024 +108,1025 @@ if (typeof(exports) !== 'undefined') { }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { var pos = (y !== NEGATIVE_ZERO); if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return 0; } } else { // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { + if (eqv(n, 0)) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean
dyoo/js-numbers
eaef780b32e1d5f2fdc06a0498c9492ddc7718a9
acos 1 == 0
diff --git a/src/js-numbers.js b/src/js-numbers.js index 40fa1fc..9c9e13e 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -124,1024 +124,1025 @@ if (typeof(exports) !== 'undefined') { }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { var pos = (y !== NEGATIVE_ZERO); if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return 0; } } else { // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return pos ? inf : neginf; } else if (lessThan(x, 0)) { return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { + if (eqv(n, 1)) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type.
dyoo/js-numbers
70c84fc2c2fbeeebec9f6e22ad0b697f5199c6bb
fixing definition of complex's isReal, isRational, and isInteger so it uses exactness
diff --git a/src/js-numbers.js b/src/js-numbers.js index 3ed6fb7..40fa1fc 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1511,1195 +1511,1195 @@ if (typeof(exports) !== 'undefined') { if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (this === NEGATIVE_ZERO) { return this; } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return FloatPoint.makeInstance(Math.floor(this.n)); return FloatPoint.makeInstance(Math.ceil(this.n)); } else { return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { - return isRational(this.r) && equals(this.i, 0); + return isRational(this.r) && eqv(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && - equals(this.i, 0)); + eqv(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ - return equals(this.i, 0); + return eqv(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(digitRegexp) && (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a diff --git a/test/tests.js b/test/tests.js index fe1431f..934237c 100644 --- a/test/tests.js +++ b/test/tests.js @@ -137,1244 +137,1248 @@ describe('fromString', { 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { // If any component of a complex is inexact, both // the real and imaginary parts get turned into // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); + assertFalse(isRational(makeComplex(makeFloat(0), makeFloat(0)))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723"))); assertTrue(isReal(makeBignum("1e1000"))); assertTrue(isReal(makeBignum("-1e1000"))); assertTrue(isReal(makeBignum("1e23784"))); assertTrue(isReal(makeBignum("-7.241e23784"))); }, 'rationals': function() { assertTrue(isReal(makeRational(0, 1))); assertTrue(isReal(makeRational(0, 12342))); assertTrue(isReal(makeRational(-2324, 12342))); assertTrue(isReal(makeRational(1, 2))); }, 'floats': function() { assertTrue(isReal(makeFloat(1.0))); assertTrue(isReal(makeFloat(25.0))); assertTrue(isReal(e)); assertTrue(isReal(pi)); assertTrue(isReal(inf)); assertTrue(isReal(negative_inf)); assertTrue(isReal(nan)); }, 'complex': function() { assertTrue(isReal(makeComplex(0, 0))); assertTrue(isReal(makeComplex(e, 0))); assertTrue(isReal(makeComplex(pi, 0))); assertTrue(isReal(makeComplex(nan, 0))); assertTrue(isReal(makeComplex(inf, 0))); assertTrue(isReal(makeComplex(negative_inf, 0))); assertFalse(isReal(makeComplex(0, 1))); assertFalse(isReal(makeComplex(0, negative_inf))); assertFalse(isReal(makeComplex(pi, inf))); assertFalse(isReal(makeComplex(234, nan))); + assertFalse(isReal(makeComplex(makeFloat(3), + makeFloat(0)))); }, 'others': function() { assertFalse(isReal("0")); assertFalse(isReal("hello")); assertFalse(isReal([])); assertFalse(isReal({})); assertFalse(isReal(false)); } }); describe('isExact', { 'fixnums': function() { assertTrue(isExact(19)); assertTrue(isExact(0)); assertTrue(isExact(-1)); assertTrue(isExact(1)); }, 'bignums': function() { assertTrue(isExact(makeBignum("0"))); assertTrue(isExact(makeBignum("1"))); assertTrue(isExact(makeBignum("-1"))); assertTrue(isExact(makeBignum("23497842398287924789232439723"))); assertTrue(isExact(makeBignum("1e1000"))); assertTrue(isExact(makeBignum("-1e1000"))); assertTrue(isExact(makeBignum("12342357892297851728921374891327893"))); assertTrue(isExact(makeBignum("4.1321e200"))); assertTrue(isExact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertTrue(isExact(makeRational(19))); assertTrue(isExact(makeRational(0))); assertTrue(isExact(makeRational(-1))); assertTrue(isExact(makeRational(1))); assertTrue(isExact(makeRational(1, 2))); assertTrue(isExact(makeRational(1, 29291))); }, 'floats': function() { assertFalse(isExact(e)); assertFalse(isExact(pi)); assertFalse(isExact(inf)); assertFalse(isExact(negative_inf)); assertFalse(isExact(nan)); assertFalse(isExact(makeFloat(0))); assertFalse(isExact(makeFloat(1111.1))); }, 'complex': function() { assertTrue(isExact(makeComplex(0, 0))); assertTrue(isExact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertFalse(isExact(makeComplex(e, makeRational(1, 17)))); assertFalse(isExact(makeComplex(makeRational(1,2), pi))); assertFalse(isExact(makeComplex(makeRational(1,2), nan))); assertFalse(isExact(makeComplex(negative_inf, nan))); } }); describe('isInexact', { 'fixnums': function() { assertFalse(isInexact(19)); assertFalse(isInexact(0)); assertFalse(isInexact(-1)); assertFalse(isInexact(1)); }, 'bignums': function() { assertFalse(isInexact(makeBignum("0"))); assertFalse(isInexact(makeBignum("1"))); assertFalse(isInexact(makeBignum("-1"))); assertFalse(isInexact(makeBignum("23497842398287924789232439723"))); assertFalse(isInexact(makeBignum("1e1000"))); assertFalse(isInexact(makeBignum("-1e1000"))); assertFalse(isInexact(makeBignum("12342357892297851728921374891327893"))); assertFalse(isInexact(makeBignum("4.1321e200"))); assertFalse(isInexact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertFalse(isInexact(makeRational(19))); assertFalse(isInexact(makeRational(0))); assertFalse(isInexact(makeRational(-1))); assertFalse(isInexact(makeRational(1))); assertFalse(isInexact(makeRational(1, 2))); assertFalse(isInexact(makeRational(1, 29291))); }, 'floats': function() { assertTrue(isInexact(e)); assertTrue(isInexact(pi)); assertTrue(isInexact(inf)); assertTrue(isInexact(negative_inf)); assertTrue(isInexact(nan)); assertTrue(isInexact(makeFloat(0))); assertTrue(isInexact(makeFloat(1111.1))); }, 'complex': function() { assertFalse(isInexact(makeComplex(0, 0))); assertFalse(isInexact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertTrue(isInexact(makeComplex(e, makeRational(1, 17)))); assertTrue(isInexact(makeComplex(makeRational(1,2), pi))); assertTrue(isInexact(makeComplex(makeRational(1,2), nan))); assertTrue(isInexact(makeComplex(negative_inf, nan))); } }); describe('isInteger', { 'fixnums': function() { assertTrue(isInteger(1)); assertTrue(isInteger(-1)); }, 'bignums': function() { assertTrue(isInteger(makeBignum("2983473189472187414789132743928148151617364"))); assertTrue(isInteger(makeBignum("-99999999999999999999999999999999999999"))); }, 'rationals': function() { assertTrue(isInteger(makeRational(1, 1))); assertFalse(isInteger(makeRational(1, 2))); assertFalse(isInteger(makeRational(9999, 10000))); assertFalse(isInteger(makeRational(9999, 1000))); }, 'floats': function() { assertFalse(isInteger(makeFloat(2.3))); assertTrue(isInteger(makeFloat(4.0))); assertFalse(isInteger(inf)); assertFalse(isInteger(negative_inf)); assertFalse(isInteger(nan)); }, 'complex': function() { assertTrue(isInteger(makeComplex(42, 0))); + assertFalse(isInteger(makeComplex(makeFloat(42), makeFloat(0)))); assertFalse(isInteger(makeComplex(42, 42))); assertFalse(isInteger(i)); assertFalse(isInteger(negative_i)); }, 'others': function() { assertFalse(isInteger("hello")); assertFalse(isInteger("0")); } }); describe('toFixnum', { 'fixnums': function() { assertEquals(42, toFixnum(42)); assertEquals(-20, toFixnum(-20)); assertEquals(0, toFixnum(0)); }, 'bignums': function() { assertEquals(123456789, toFixnum(makeBignum("123456789"))); assertEquals(0, toFixnum(makeBignum("0"))); assertEquals(-123, toFixnum(makeBignum("-123"))); assertEquals(123456, toFixnum(makeBignum("123456"))); // We're dealing with big numbers, where the numerical error // makes it difficult to compare for equality. We just go for // percentage and see that it is ok. assertTrue(diffPercent(1e200, toFixnum(makeBignum("1e200"))) < 1e-10); assertTrue(diffPercent(-1e200, toFixnum(makeBignum("-1e200"))) < 1e-10); }, 'rationals': function() { assertEquals(0, toFixnum(zero)); assertEquals(17/2, toFixnum(makeRational(17, 2))); assertEquals(1926/3, toFixnum(makeRational(1926, 3))); assertEquals(-11150/17, toFixnum(makeRational(-11150, 17))); }, 'floats': function() { assertEquals(12345.6789, toFixnum(makeFloat(12345.6789))); assertEquals(Math.PI, toFixnum(pi)); assertEquals(Math.E, toFixnum(e)); assertEquals(Number.POSITIVE_INFINITY, toFixnum(inf)); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(negative_inf)); assertTrue(isNaN(toFixnum(nan))); }, 'complex': function() { assertFails(function() { toFixnum(makeComplex(2, 1)); }); assertFails(function() { toFixnum(i); }); assertFails(function() { toFixnum(negative_i); }); assertEquals(2, toFixnum(makeComplex(2, 0))); assertEquals(1/2, toFixnum(makeComplex(makeRational(1, 2), 0))); assertEquals(Number.POSITIVE_INFINITY, toFixnum(makeComplex(inf, 0))); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(makeComplex(negative_inf, 0))); assertTrue(isNaN(toFixnum(makeComplex(nan, 0)))); } }); describe('toExact', { 'fixnums': function() { assertEquals(1792, toExact(1792)); assertEquals(0, toExact(0)); assertEquals(-1, toExact(-1)); }, 'bignums': function() { assertEquals(makeBignum("4.2e100"), toExact(makeBignum("4.2e100"))); assertEquals(makeBignum("0"), toExact(makeBignum("0"))); assertEquals(makeBignum("1"), toExact(makeBignum("1"))); assertEquals(makeBignum("-1"), toExact(makeBignum("-1"))); assertEquals(makeBignum("-12345"), toExact(makeBignum("-12345"))); assertEquals(makeBignum("-1.723e500"), toExact(makeBignum("-1.723e500"))); }, 'rationals': function() { assertEquals(makeRational(1, 2), toExact(makeRational(1, 2))); assertEquals(makeRational(1, 9999), toExact(makeRational(1, 9999))); assertEquals(makeRational(0, 1), toExact(makeRational(0, 9999))); assertEquals(makeRational(-290, 1), toExact(makeRational(-290, 1))); }, 'floats': function() { assertEquals(makeRational(1, 2), toExact(makeFloat(0.5))); assertEquals(makeRational(1, 10), toExact(makeFloat(0.1))); assertEquals(makeRational(9, 10), toExact(makeFloat(0.9))); assertTrue(isExact(toExact(makeFloat(10234.7)))); assertTrue(diffPercent(makeRational(102347, 10), toExact(makeFloat(10234.7))) < 1); assertEquals(-1, toExact(makeFloat(-1))); assertEquals(0, toExact(makeFloat(0))); assertEquals(1024, toExact(makeFloat(1024))); assertFails(function() { toExact(nan); }); assertFails(function() { toExact(inf); }); assertFails(function() { toExact(negative_inf); }); }, 'complex': function() { assertEquals(0, toExact(makeComplex(0, 0))); assertEquals(99, toExact(makeComplex(99, 0))); assertEquals(makeRational(-1, 2), toExact(makeComplex(makeRational(-1, 2), 0))); assertEquals(makeRational(1, 4), toExact(makeComplex(makeFloat(.25), 0))); assertFails(function() { toExact(makeComplex(nan, 0)); }); assertFails(function() { toExact(makeComplex(inf, 0)); }); assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); assertTrue(eqv(toExact(makeComplex(0, 1)), makeComplex(0, 1))); assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1));
dyoo/js-numbers
d3bf179f4a2ccec6b07247abe5158b9b59a79a9e
fixing round to preserve inexactness
diff --git a/src/js-numbers.js b/src/js-numbers.js index 227f543..3ed6fb7 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1446,1030 +1446,1033 @@ if (typeof(exports) !== 'undefined') { Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } else { return FloatPoint.makeInstance(Math.floor(this.n)); } }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } else if (this === NEGATIVE_ZERO) { return this; } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { + if (this === NEGATIVE_ZERO) { + return this; + } if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) - return fromFixnum(Math.floor(this.n)); - return fromFixnum(Math.ceil(this.n)); + return FloatPoint.makeInstance(Math.floor(this.n)); + return FloatPoint.makeInstance(Math.ceil(this.n)); } else { - return fromFixnum(Math.round(this.n)); + return FloatPoint.makeInstance(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(digitRegexp) && (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff;
dyoo/js-numbers
8a308a25935b3905db9c4e87ca4d245fb3574f52
fixing one of the tests with division
diff --git a/test/tests.js b/test/tests.js index c4ad425..fe1431f 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2779,1071 +2779,1072 @@ describe('realPart', { 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('repeating decimals', { tests: function() { assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); - assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); + assertEqv(divide(makeFloat(1),makeFloat(0)), + inf); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); assertEquals("5.0+0.0i", (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", (makeComplex(5, 1)).toString()); assertEquals("4-2i", (makeComplex(4, -2)).toString()); }, testQuotient : function(){ assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(36), makeRational(7)), makeRational(5))); assertTrue(eqv(1, quotient(7, 5))); }, testRemainder : function(){ assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, modulo(n1, n2)); assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(isReal(pi)); assertTrue(isReal(1)); assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!isReal("hi")); }, testRound : function(){ assertTrue(equals(round(makeFloat(3.499999)), - makeFloat(3))); + makeFloat(3))); assertTrue(equals(round(makeFloat(3.5)), - makeFloat(4))); + makeFloat(4))); assertTrue(equals(round(makeFloat(3.51)), - makeFloat(4))); + makeFloat(4))); assertTrue(equals(round(makeRational(3)), - makeRational(3))); - + makeRational(3))); + assertTrue(equals(round(makeRational(17, 4)), - makeRational(4))); - - + makeRational(4))); + + assertTrue(equals(round(makeRational(-17, 4)), - makeRational(-4))); + makeRational(-4))); }, // testSgn : function(){ // assertTrue(equals(sgn(makeFloat(4)), 1)); // assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); // assertTrue(equals(sgn(0), 0)); // }, // testZero_question_ : function(){ // assertTrue(Kernel.zero_question_(0)); // assertTrue(!Kernel.zero_question_(1)); // assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); // } });
dyoo/js-numbers
260da58dc1b7757afedc2b4f5b5f228961925f8e
correcting bugs with ceiling tests
diff --git a/test/tests.js b/test/tests.js index 0c06ed0..c4ad425 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1940,1084 +1940,1086 @@ describe('lessThan', { }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); assertEqv(makeFloat(1), floor(makeFloat(1.0))); assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); assertEqv(makeFloat(1), floor(makeFloat(1.1))); assertEqv(makeFloat(1), floor(makeFloat(1.999))); assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); assertEqv(makeFloat(1234567891234567), floor(makeFloat(1234567891234567.8))); assertEqv(makeFloat(-1234567891234568), floor(makeFloat(-1234567891234567.8))); assertEqv(nan, floor(nan)); assertEqv(inf, floor(inf)); assertEqv(negative_inf, floor(negative_inf)); assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeFloat(-2), floor(makeComplex(makeFloat(-1.999), makeFloat(0.0))))); assertTrue(eqv(makeFloat(1234567891234567), floor(makeComplex(makeFloat(1234567891234567.8), makeFloat(0))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { - assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); - assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); - assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); - assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); - assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); - assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); - assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); - assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); - assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); - assertEquals(nan, ceiling(nan)); - assertEquals(inf, ceiling(inf)); - assertEquals(negative_inf, ceiling(negative_inf)); - assertEquals(negative_zero, ceiling(negative_zero)); + assertEqv(makeFloat(0), ceiling(makeFloat(0.0))); + assertEqv(makeFloat(1), ceiling(makeFloat(1.0))); + assertEqv(makeFloat(-1), ceiling(makeFloat(-1.0))); + assertEqv(makeFloat(2), ceiling(makeFloat(1.1))); + assertEqv(makeFloat(2), ceiling(makeFloat(1.999))); + assertEqv(makeFloat(-1), ceiling(makeFloat(-1.999))); + assertEqv(makeFloat(123457), ceiling(makeFloat(123456.789))); + assertEqv(makeFloat(1234567891234568), + ceiling(makeFloat(1234567891234567.8))); + assertEqv(makeFloat(-1234567891234567), + ceiling(makeFloat(-1234567891234567.8))); + assertEqv(nan, ceiling(nan)); + assertEqv(inf, ceiling(inf)); + assertEqv(negative_inf, ceiling(negative_inf)); + assertEqv(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); - assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); + assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); - assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), - makeBignum("0"))))); - assertTrue(eqv(makeBignum("1234567891234568"), + assertTrue(eqv(makeFloat(-1), ceiling(makeComplex(makeFloat(-1.999), + makeFloat(0))))); + assertTrue(eqv(makeFloat(1234567891234568), ceiling(makeComplex(makeFloat(1234567891234567.8), - makeBignum("0"))))); + makeFloat(0))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7"))));
dyoo/js-numbers
c9dd9c829f26bdcb1cda2784b2778e01738677d0
repairing tests with floor
diff --git a/src/js-numbers.js b/src/js-numbers.js index e12ac8a..227f543 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1312,1033 +1312,1037 @@ if (typeof(exports) !== 'undefined') { _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; + } else if (this === NEGATIVE_ZERO) { + return this; + } else { + return FloatPoint.makeInstance(Math.floor(this.n)); } - return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; - } - return fromFixnum(Math.ceil(this.n)); + } else if (this === NEGATIVE_ZERO) { + return this; + } return FloatPoint.makeInstance(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ diff --git a/test/tests.js b/test/tests.js index c00565a..0c06ed0 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,533 +1,538 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; + +var assertEqv = function(x, y) { + value_of(eqv(x, y)).should_be_true(); +}; + var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { // FIXME: add tests for polar construction }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, @@ -1796,1085 +1801,1087 @@ describe('lessThanOrEqual', { }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); assertTrue(eqv(1, floor(makeRational(7, 5)))); }, 'floats': function() { - assertEquals(makeBignum("0"), floor(makeFloat(0.0))); - assertEquals(makeBignum("1"), floor(makeFloat(1.0))); - assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); - assertEquals(makeBignum("1"), floor(makeFloat(1.1))); - assertEquals(makeBignum("1"), floor(makeFloat(1.999))); - assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); - assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); - assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); - assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); - assertEquals(nan, floor(nan)); - assertEquals(inf, floor(inf)); - assertEquals(negative_inf, floor(negative_inf)); - assertEquals(negative_zero, floor(negative_zero)); + assertEqv(makeFloat(0.0), floor(makeFloat(0.0))); + assertEqv(makeFloat(1), floor(makeFloat(1.0))); + assertEqv(makeFloat(-1), floor(makeFloat(-1.0))); + assertEqv(makeFloat(1), floor(makeFloat(1.1))); + assertEqv(makeFloat(1), floor(makeFloat(1.999))); + assertEqv(makeFloat(-2), floor(makeFloat(-1.999))); + assertEqv(makeFloat(123456), floor(makeFloat(123456.789))); + assertEqv(makeFloat(1234567891234567), + floor(makeFloat(1234567891234567.8))); + assertEqv(makeFloat(-1234567891234568), + floor(makeFloat(-1234567891234567.8))); + assertEqv(nan, floor(nan)); + assertEqv(inf, floor(inf)); + assertEqv(negative_inf, floor(negative_inf)); + assertEqv(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); - assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); + assertFails(function() { floor(makeComplex(makeFloat(4.25), makeFloat(1.5)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); - assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), - makeBignum("0"))))); - assertTrue(eqv(makeBignum("1234567891234567"), + assertTrue(eqv(makeFloat(-2), floor(makeComplex(makeFloat(-1.999), + makeFloat(0.0))))); + assertTrue(eqv(makeFloat(1234567891234567), floor(makeComplex(makeFloat(1234567891234567.8), - makeBignum("0"))))); + makeFloat(0))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', {
dyoo/js-numbers
448e17c70399b874c8cee6362c33c1420ee0584d
fixing some division-by-zero bugs
diff --git a/src/js-numbers.js b/src/js-numbers.js index 0b0cc6a..e12ac8a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,837 +1,841 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { - return (eqv(y, INEXACT_ZERO))}, + return (eqv(y, INEXACT_ZERO) || eqv(y, NEGATIVE_ZERO))}, onYSpecialCase: function(x, y) { + var pos = (y !== NEGATIVE_ZERO); + + if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { - return inf; + return pos ? inf : neginf; } else if (lessThan(x, 0)) { - return neginf; + return pos ? neginf : inf; } else { return 0; } } else { + // both x and y are inexact if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { - return inf; + return pos ? inf : neginf; } else if (lessThan(x, 0)) { - return neginf; + return pos ? neginf : inf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; diff --git a/test/tests.js b/test/tests.js index 6fe6efd..c00565a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1205,1034 +1205,1033 @@ describe('add', { assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { assertTrue(eqv(divide(makeComplex(makeFloat(1e300), makeFloat(1e300)), makeComplex(makeFloat(4e300), makeFloat(4e300))), makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); - assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); - assertTrue(eqv(negative_inf, divide(1, negative_zero))); - - assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); - assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); - assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); - assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); - - assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); - assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); + assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); + assertTrue(eqv(negative_inf, divide(1, negative_zero))); + + assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); + assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); + assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); + assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); + assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); + assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2)));
dyoo/js-numbers
38c6cb56bb6e7662661b8d37a7506d2a94a440f0
trying to fix some of the cases involving zero
diff --git a/src/js-numbers.js b/src/js-numbers.js index b5d8632..0b0cc6a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,2668 +1,2669 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) - throwRuntimeError("division by zero", x, y); + throwRuntimeError("/: division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }, { isYSpecialCase: function(y) { - return (isInexact(y) && isReal(y) && equals(y, 0))}, + return (eqv(y, INEXACT_ZERO))}, onYSpecialCase: function(x, y) { if (isReal(x)) { if (isExact(x)) { if (greaterThan(x, 0)) { return inf; } else if (lessThan(x, 0)) { return neginf; } else { return 0; } } else { if (isNaN(toFixnum(x))) { return NaN; } else if (greaterThan(x, 0)) { return inf; } else if (lessThan(x, 0)) { return neginf; } else { return NaN; } } } else { if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return x.divide(y); } } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( - "greaterThanOrEqual: couldn't be applied to complex number", x, y); + ">=: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) - throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); + throwRuntimeError("<=: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) - throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); + throwRuntimeError(">: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) - throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); + throwRuntimeError("<: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { - throwRuntimeError("division by zero", this, other); + throwRuntimeError("/: division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); + var INEXACT_ZERO = new FloatPoint(0.0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { - return throwRuntimeError("division by zero", this, other); + return throwRuntimeError("/: division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. - var down = multiply(other, con); + var down = realPart(multiply(other, con)); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(digitRegexp) && (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; diff --git a/test/tests.js b/test/tests.js index 67fdfd4..6fe6efd 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1192,1024 +1192,1029 @@ describe('add', { 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { + assertTrue(eqv(divide(makeComplex(makeFloat(1e300), + makeFloat(1e300)), + makeComplex(makeFloat(4e300), + makeFloat(4e300))), + makeFloat(.25))) // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7))));
dyoo/js-numbers
5491aefcfdf954c61b82aa1eb109015dfaf742e8
trying to treat divisino by zero more carefully
diff --git a/src/js-numbers.js b/src/js-numbers.js index 1ddb34d..0d30bfe 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,817 +1,847 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); + }, + { isYSpecialCase: function(y) { + return (isInexact(y) && isReal(y) && equals(y, 0))}, + onYSpecialCase: function(x, y) { + if (isReal(x)) { + if (isExact(x)) { + if (greaterThan(x, 0)) { + return inf; + } else if (lessThan(x, 0)) { + return neginf; + } else { + return 0; + } + } else { + if (isNaN(toFixnum(x))) { + return NaN; + } else if (greaterThan(x, 0)) { + return inf; + } else if (lessThan(x, 0)) { + return neginf; + } else { + return NaN; + } + } + } else { + if (x.level < y.level) x = x.liftTo(y); + if (y.level < x.level) y = y.liftTo(x); + return x.divide(y); + } + } }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { diff --git a/test/tests.js b/test/tests.js index 1e4fc71..8c38a6a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1215,1025 +1215,1025 @@ describe('add', { assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); - assertTrue(eqv(negative_zero, + assertTrue(eqv(nan, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1"))));
dyoo/js-numbers
40537a3dc1c698a7b3f4b825dda3f67b5ed19057
corrections to fromString
diff --git a/src/js-numbers.js b/src/js-numbers.js index 1ddb34d..2281f9f 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1809,1049 +1809,1051 @@ if (typeof(exports) !== 'undefined') { FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } if (isInexact(r) || isInexact(i)) { r = toInexact(r); i = toInexact(i); } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); + var digitRegexp = new RegExp("\\d"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } - if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { + if (x.match(digitRegexp) && + (x.match(flonumRegexp) || x.match(bignumScientificPattern))) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; if ( this.s < 0 ) { r = a.t - i; } else { r = i - a.t; } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff;
dyoo/js-numbers
db4a83dec70e1969c4f6c6dec7a6755d3fc0e079
our assertFalse function is wrong.
diff --git a/test/tests.js b/test/tests.js index a3fb2ac..0852ba3 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,539 +1,539 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { - value_of(aVal).should_be_false(); + value_of(aVal === false).should_be_true(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { // FIXME: add tests for polar construction }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false();
dyoo/js-numbers
e8b27c39ccef3d7c98b7e45461905de8a18d5750
adding some tests for jsnums
diff --git a/test/tests.js b/test/tests.js index 1e4fc71..a3fb2ac 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1785,1024 +1785,1027 @@ describe('greaterThanOrEqual', { } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); + + assertTrue(eqv(1, + floor(makeRational(7, 5)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { @@ -3235,595 +3238,599 @@ describe('old tests from Moby Scheme', { assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); assertEquals("5.0+0.0i", (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", (makeComplex(5, 1)).toString()); assertEquals("4-2i", (makeComplex(4, -2)).toString()); }, testQuotient : function(){ assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(36), makeRational(7)), makeRational(5))); + + + + assertTrue(eqv(1, quotient(7, 5))); }, testRemainder : function(){ assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, modulo(n1, n2)); assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(isReal(pi)); assertTrue(isReal(1)); assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!isReal("hi")); }, testRound : function(){ assertTrue(equals(round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(round(makeRational(3)), makeRational(3))); assertTrue(equals(round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(round(makeRational(-17, 4)), makeRational(-4))); }, // testSgn : function(){ // assertTrue(equals(sgn(makeFloat(4)), 1)); // assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); // assertTrue(equals(sgn(0), 0)); // }, // testZero_question_ : function(){ // assertTrue(Kernel.zero_question_(0)); // assertTrue(!Kernel.zero_question_(1)); // assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); // } });
dyoo/js-numbers
ed320ccc61cd20da66b84e9ccdee8138a78f792e
fixing implementation of integer quotient
diff --git a/src/js-numbers.js b/src/js-numbers.js index 01076bf..1ddb34d 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -490,1025 +490,1025 @@ if (typeof(exports) !== 'undefined') { }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { - return ((m / n) - ((m % n) / n)); + return ((m - (m % n))/ n); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; @@ -3337,670 +3337,668 @@ if (typeof(exports) !== 'undefined') { Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. ////////////////////////////////////////////////////////////////////// // toRepeatingDecimal: jsnum jsnum -> [string, string, string] // // Given the numerator and denominator parts of a rational, // produces the repeating-decimal representation, where the first // part are the digits before the decimal, the second are the // non-repeating digits after the decimal, and the third are the // remaining repeating decimals. var toRepeatingDecimal = (function() { - var getResidue = function(remainder, divisor) { + var getResidue = function(r, d) { var digits = []; var seenRemainders = {}; - seenRemainders[remainder] = true; + seenRemainders[r] = true; while(true) { var nextDigit = quotient( - multiply(remainder, 10), divisor); + multiply(r, 10), d); var nextRemainder = remainder( - multiply(remainder, 10), - divisor); - + multiply(r, 10), + d); digits.push(nextDigit.toString()); if (seenRemainders[nextRemainder]) { - remainder = nextRemainder; + r = nextRemainder; break; } else { seenRemainders[nextRemainder] = true; - remainder = nextRemainder; + r = nextRemainder; } } - var firstRepeatingRemainder = remainder; + var firstRepeatingRemainder = r; var repeatingDigits = []; while (true) { - var nextDigit = quotient( - multiply(remainder, 10), divisor); + var nextDigit = quotient(multiply(r, 10), d); var nextRemainder = remainder( - multiply(remainder, 10), - divisor); + multiply(r, 10), + d); repeatingDigits.push(nextDigit.toString()); if (equals(nextRemainder, firstRepeatingRemainder)) { break; } else { - remainder = nextRemainder; + r = nextRemainder; } }; var digitString = digits.join(''); var repeatingDigitString = repeatingDigits.join(''); while (digitString.length >= repeatingDigitString.length && (digitString.substring( digitString.length - repeatingDigitString.length) === repeatingDigitString)) { digitString = digitString.substring( 0, digitString.length - repeatingDigitString.length); } return [digitString, repeatingDigitString]; }; return function(n, d) { if (! isInteger(n)) { throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + " is not an integer."); } if (! isInteger(d)) { throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + " is not an integer."); } if (equals(d, 0)) { throwRuntimeError('toRepeatingDecimal: d equals 0'); } if (lessThan(d, 0)) { throwRuntimeError('toRepeatingDecimal: d < 0'); } - var sign = (lessThan(n, 0) ? "-" : ""); - n = abs(n); - var beforeDecimalPoint = sign + quotient(n, d); - var afterDecimals = getResidue(remainder(n, d), d); - return [beforeDecimalPoint].concat(afterDecimals); + var sign = (lessThan(n, 0) ? "-" : ""); + n = abs(n); + var beforeDecimalPoint = sign + quotient(n, d); + var afterDecimals = getResidue(remainder(n, d), d); + return [beforeDecimalPoint].concat(afterDecimals); }; })(); ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })(); diff --git a/test/tests.js b/test/tests.js index 6b96a56..1e4fc71 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2666,1024 +2666,1048 @@ describe('acos', { 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); +describe('repeating decimals', { + tests: function() { + assertEquals(['1', '', '0'], toRepeatingDecimal(1, 1)); + assertEquals(['0', '5', '0'], toRepeatingDecimal(1, 2)); + assertEquals(['0', '', '3'], toRepeatingDecimal(1, 3)); + assertEquals(['0', '25', '0'], toRepeatingDecimal(1, 4)); + assertEquals(['0', '2', '0'], toRepeatingDecimal(1, 5)); + assertEquals(['0', '1', '6'], toRepeatingDecimal(1, 6)); + assertEquals(['0', '', '142857'], toRepeatingDecimal(1, 7)); + assertEquals(['0', '125', '0'], toRepeatingDecimal(1, 8)); + assertEquals(['0', '', '1'], toRepeatingDecimal(1, 9)); + assertEquals(['0', '1', '0'], toRepeatingDecimal(1, 10)); + assertEquals(['0', '', '09'], toRepeatingDecimal(1, 11)); + assertEquals(['0', '08', '3'], toRepeatingDecimal(1, 12)); + assertEquals(['0', '', '076923'], toRepeatingDecimal(1, 13)); + assertEquals(['0', '0', '714285'], toRepeatingDecimal(1, 14)); + assertEquals(['0', '0', '6'], toRepeatingDecimal(1, 15)); + assertEquals(['0', '0625', '0'], toRepeatingDecimal(1, 16)); + assertEquals(['0', '', '0588235294117647'], toRepeatingDecimal(1, 17)); + assertEquals(['5', '8', '144'], toRepeatingDecimal(3227, 555)); + } +}); + + describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); assertEquals("5.0+0.0i",
dyoo/js-numbers
c5629f91f465d87384a9a0dc8de0f9da052a3beb
adding implementation for repeating decimal representation.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 3a7a4e8..01076bf 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,618 +1,618 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: - return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); + throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if ( eqv(n, 1) ) { return 0; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { @@ -3328,594 +3328,679 @@ if (typeof(exports) !== 'undefined') { // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.isInexact = function() { return false; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. + ////////////////////////////////////////////////////////////////////// + // toRepeatingDecimal: jsnum jsnum -> [string, string, string] + // + // Given the numerator and denominator parts of a rational, + // produces the repeating-decimal representation, where the first + // part are the digits before the decimal, the second are the + // non-repeating digits after the decimal, and the third are the + // remaining repeating decimals. + var toRepeatingDecimal = (function() { + var getResidue = function(remainder, divisor) { + var digits = []; + var seenRemainders = {}; + seenRemainders[remainder] = true; + while(true) { + var nextDigit = quotient( + multiply(remainder, 10), divisor); + var nextRemainder = remainder( + multiply(remainder, 10), + divisor); + + digits.push(nextDigit.toString()); + if (seenRemainders[nextRemainder]) { + remainder = nextRemainder; + break; + } else { + seenRemainders[nextRemainder] = true; + remainder = nextRemainder; + } + } + + var firstRepeatingRemainder = remainder; + var repeatingDigits = []; + while (true) { + var nextDigit = quotient( + multiply(remainder, 10), divisor); + var nextRemainder = remainder( + multiply(remainder, 10), + divisor); + repeatingDigits.push(nextDigit.toString()); + if (equals(nextRemainder, firstRepeatingRemainder)) { + break; + } else { + remainder = nextRemainder; + } + }; + + var digitString = digits.join(''); + var repeatingDigitString = repeatingDigits.join(''); + + while (digitString.length >= repeatingDigitString.length && + (digitString.substring( + digitString.length - repeatingDigitString.length) + === repeatingDigitString)) { + digitString = digitString.substring( + 0, digitString.length - repeatingDigitString.length); + } + + return [digitString, repeatingDigitString]; + + }; + + return function(n, d) { + if (! isInteger(n)) { + throwRuntimeError('toRepeatingDecimal: n ' + n.toString() + + " is not an integer."); + } + if (! isInteger(d)) { + throwRuntimeError('toRepeatingDecimal: d ' + d.toString() + + " is not an integer."); + } + if (equals(d, 0)) { + throwRuntimeError('toRepeatingDecimal: d equals 0'); + } + if (lessThan(d, 0)) { + throwRuntimeError('toRepeatingDecimal: d < 0'); + } + var sign = (lessThan(n, 0) ? "-" : ""); + n = abs(n); + var beforeDecimalPoint = sign + quotient(n, d); + var afterDecimals = getResidue(remainder(n, d), d); + return [beforeDecimalPoint].concat(afterDecimals); + }; + })(); + ////////////////////////////////////////////////////////////////////// // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; + Numbers['toRepeatingDecimal'] = toRepeatingDecimal; })();
dyoo/js-numbers
5ca9fc4635c706ea6fc07c345a3a0ea358a6a9e7
fixing issue with bignums
diff --git a/src/js-numbers.js b/src/js-numbers.js index 35a356a..3a7a4e8 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,521 +1,521 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { - this['jsnums'] = {}; + this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } //var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; //var Numbers = jsnums; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if ( eqv(n, 0) ) { return 1; } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); @@ -761,1025 +761,1025 @@ if (typeof(exports) !== 'undefined') { // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { - return Rational.makeInstance(-this.n, d) + return Rational.makeInstance(-this.n, this.d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var intPart = parseInt(match[1]); var fracPart = parseInt(match[2]); var tenToDecimalPlaces = Math.pow(10, match[2].length); return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), tenToDecimalPlaces); } else { return this.n; } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; var partialResult = this.n.toString(); if (! partialResult.match('\\.')) { return partialResult + ".0"; } else { return partialResult; } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); var multFactor = factorToInt / extraFactor; return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { var afterDecimal = parseInt(match[2]); var factorToInt = Math.pow(10, match[2].length); var extraFactor = _integerGcd(factorToInt, afterDecimal); return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { return FloatPoint.makeInstance(1); } }; @@ -2070,1025 +2070,1030 @@ if (typeof(exports) !== 'undefined') { }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; - r = i-a.t; + if ( this.s < 0 ) { + r = a.t - i; + } + else { + r = i - a.t; + } if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1<<i)) > 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]; } // (public) return value as byte function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = [], t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; this.fromString(x,256); } } // (public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = []; r[0] = this.s; var p = this.DB-(i*this.DB)%8, d, k = 0; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<<p)-1))<<(8-p); d |= this[--i]>>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
dyoo/js-numbers
8658df7dcd8b84a636420877ab969b880b19aef1
updating test cases; complex numbers have consistent inexactness
diff --git a/src/js-numbers.js b/src/js-numbers.js index d02d84f..35a356a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,2652 +1,2682 @@ // Scheme numbers. + var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } +//var jsnums = {}; // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; + //var Numbers = jsnums; + // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isExact: scheme-number -> boolean var isInexact = function(n) { if (typeof(n) === 'number') { return false; } else { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { + if ( eqv(n, 0) ) { + return 1; + } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { + if ( eqv(n, 1) ) { + return 0; + } if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.isInexact = function() { return false; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } - var fracPart = this.n - Math.floor(this.n); - var intPart = this.n - fracPart; - return add(intPart, - Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); + + var stringRep = this.n.toString(); + var match = stringRep.match(/^(.*)\.(.*)$/); + if (match) { + var intPart = parseInt(match[1]); + var fracPart = parseInt(match[2]); + var tenToDecimalPlaces = Math.pow(10, match[2].length); + return Rational.makeInstance(Math.round(this.n * tenToDecimalPlaces), + tenToDecimalPlaces); + } + else { + return this.n; + } }; FloatPoint.prototype.toInexact = function() { return this; }; FloatPoint.prototype.isInexact = function() { return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; - if (this.n === 0) - return "0.0"; - return this.n.toString(); + var partialResult = this.n.toString(); + if (! partialResult.match('\\.')) { + return partialResult + ".0"; + } else { + return partialResult; + } }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { - return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); + var afterDecimal = parseInt(match[2]); + var factorToInt = Math.pow(10, match[2].length); + var extraFactor = _integerGcd(factorToInt, afterDecimal); + var multFactor = factorToInt / extraFactor; + return FloatPoint.makeInstance( Math.round(this.n * multFactor) ); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { - return FloatPoint.makeInstance(Math.pow(10, match[2].length)); + var afterDecimal = parseInt(match[2]); + var factorToInt = Math.pow(10, match[2].length); + var extraFactor = _integerGcd(factorToInt, afterDecimal); + return FloatPoint.makeInstance( Math.round(factorToInt/extraFactor) ); } else { - return FloatPoint.makeInstance(1.0); + return FloatPoint.makeInstance(1); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } + if (isInexact(r) || isInexact(i)) { + r = toInexact(r); + i = toInexact(i); + } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { - if (! this.isReal()) { - throwRuntimeError("inexact->exact: expects argument of type real number", this); - } - return toExact(this.r); + return Complex.makeInstance( toExact(this.r), toExact(this.i) ); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.isInexact = function() { return isInexact(this.r) || isInexact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); - var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); + var i = divide(this.i, sqrt(multiply(r_plus_x, 2))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; diff --git a/test/tests.js b/test/tests.js index 9dabbd7..6b96a56 100644 --- a/test/tests.js +++ b/test/tests.js @@ -65,1434 +65,1435 @@ describe('rational constructions', { 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { // FIXME: add tests for polar construction }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { + // If any component of a complex is inexact, both + // the real and imaginary parts get turned into + // inexact quantities. value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), - makeFloat(1.1)))).should_be_false(); + makeFloat(1.1)))).should_be_true(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723"))); assertTrue(isReal(makeBignum("1e1000"))); assertTrue(isReal(makeBignum("-1e1000"))); assertTrue(isReal(makeBignum("1e23784"))); assertTrue(isReal(makeBignum("-7.241e23784"))); }, 'rationals': function() { assertTrue(isReal(makeRational(0, 1))); assertTrue(isReal(makeRational(0, 12342))); assertTrue(isReal(makeRational(-2324, 12342))); assertTrue(isReal(makeRational(1, 2))); }, 'floats': function() { assertTrue(isReal(makeFloat(1.0))); assertTrue(isReal(makeFloat(25.0))); assertTrue(isReal(e)); assertTrue(isReal(pi)); assertTrue(isReal(inf)); assertTrue(isReal(negative_inf)); assertTrue(isReal(nan)); }, 'complex': function() { assertTrue(isReal(makeComplex(0, 0))); assertTrue(isReal(makeComplex(e, 0))); assertTrue(isReal(makeComplex(pi, 0))); assertTrue(isReal(makeComplex(nan, 0))); assertTrue(isReal(makeComplex(inf, 0))); assertTrue(isReal(makeComplex(negative_inf, 0))); assertFalse(isReal(makeComplex(0, 1))); assertFalse(isReal(makeComplex(0, negative_inf))); assertFalse(isReal(makeComplex(pi, inf))); assertFalse(isReal(makeComplex(234, nan))); }, 'others': function() { assertFalse(isReal("0")); assertFalse(isReal("hello")); assertFalse(isReal([])); assertFalse(isReal({})); assertFalse(isReal(false)); } }); describe('isExact', { 'fixnums': function() { assertTrue(isExact(19)); assertTrue(isExact(0)); assertTrue(isExact(-1)); assertTrue(isExact(1)); }, 'bignums': function() { assertTrue(isExact(makeBignum("0"))); assertTrue(isExact(makeBignum("1"))); assertTrue(isExact(makeBignum("-1"))); assertTrue(isExact(makeBignum("23497842398287924789232439723"))); assertTrue(isExact(makeBignum("1e1000"))); assertTrue(isExact(makeBignum("-1e1000"))); assertTrue(isExact(makeBignum("12342357892297851728921374891327893"))); assertTrue(isExact(makeBignum("4.1321e200"))); assertTrue(isExact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertTrue(isExact(makeRational(19))); assertTrue(isExact(makeRational(0))); assertTrue(isExact(makeRational(-1))); assertTrue(isExact(makeRational(1))); assertTrue(isExact(makeRational(1, 2))); assertTrue(isExact(makeRational(1, 29291))); }, 'floats': function() { assertFalse(isExact(e)); assertFalse(isExact(pi)); assertFalse(isExact(inf)); assertFalse(isExact(negative_inf)); assertFalse(isExact(nan)); assertFalse(isExact(makeFloat(0))); assertFalse(isExact(makeFloat(1111.1))); }, 'complex': function() { assertTrue(isExact(makeComplex(0, 0))); assertTrue(isExact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertFalse(isExact(makeComplex(e, makeRational(1, 17)))); assertFalse(isExact(makeComplex(makeRational(1,2), pi))); assertFalse(isExact(makeComplex(makeRational(1,2), nan))); assertFalse(isExact(makeComplex(negative_inf, nan))); } }); describe('isInexact', { 'fixnums': function() { assertFalse(isInexact(19)); assertFalse(isInexact(0)); assertFalse(isInexact(-1)); assertFalse(isInexact(1)); }, 'bignums': function() { assertFalse(isInexact(makeBignum("0"))); assertFalse(isInexact(makeBignum("1"))); assertFalse(isInexact(makeBignum("-1"))); assertFalse(isInexact(makeBignum("23497842398287924789232439723"))); assertFalse(isInexact(makeBignum("1e1000"))); assertFalse(isInexact(makeBignum("-1e1000"))); assertFalse(isInexact(makeBignum("12342357892297851728921374891327893"))); assertFalse(isInexact(makeBignum("4.1321e200"))); assertFalse(isInexact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertFalse(isInexact(makeRational(19))); assertFalse(isInexact(makeRational(0))); assertFalse(isInexact(makeRational(-1))); assertFalse(isInexact(makeRational(1))); assertFalse(isInexact(makeRational(1, 2))); assertFalse(isInexact(makeRational(1, 29291))); }, 'floats': function() { assertTrue(isInexact(e)); assertTrue(isInexact(pi)); assertTrue(isInexact(inf)); assertTrue(isInexact(negative_inf)); assertTrue(isInexact(nan)); assertTrue(isInexact(makeFloat(0))); assertTrue(isInexact(makeFloat(1111.1))); }, 'complex': function() { assertFalse(isInexact(makeComplex(0, 0))); assertFalse(isInexact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertTrue(isInexact(makeComplex(e, makeRational(1, 17)))); assertTrue(isInexact(makeComplex(makeRational(1,2), pi))); assertTrue(isInexact(makeComplex(makeRational(1,2), nan))); assertTrue(isInexact(makeComplex(negative_inf, nan))); } }); describe('isInteger', { 'fixnums': function() { assertTrue(isInteger(1)); assertTrue(isInteger(-1)); }, 'bignums': function() { assertTrue(isInteger(makeBignum("2983473189472187414789132743928148151617364"))); assertTrue(isInteger(makeBignum("-99999999999999999999999999999999999999"))); }, 'rationals': function() { assertTrue(isInteger(makeRational(1, 1))); assertFalse(isInteger(makeRational(1, 2))); assertFalse(isInteger(makeRational(9999, 10000))); assertFalse(isInteger(makeRational(9999, 1000))); }, 'floats': function() { assertFalse(isInteger(makeFloat(2.3))); assertTrue(isInteger(makeFloat(4.0))); assertFalse(isInteger(inf)); assertFalse(isInteger(negative_inf)); assertFalse(isInteger(nan)); }, 'complex': function() { assertTrue(isInteger(makeComplex(42, 0))); assertFalse(isInteger(makeComplex(42, 42))); assertFalse(isInteger(i)); assertFalse(isInteger(negative_i)); }, 'others': function() { assertFalse(isInteger("hello")); assertFalse(isInteger("0")); } }); describe('toFixnum', { 'fixnums': function() { assertEquals(42, toFixnum(42)); assertEquals(-20, toFixnum(-20)); assertEquals(0, toFixnum(0)); }, 'bignums': function() { assertEquals(123456789, toFixnum(makeBignum("123456789"))); assertEquals(0, toFixnum(makeBignum("0"))); assertEquals(-123, toFixnum(makeBignum("-123"))); assertEquals(123456, toFixnum(makeBignum("123456"))); // We're dealing with big numbers, where the numerical error // makes it difficult to compare for equality. We just go for // percentage and see that it is ok. assertTrue(diffPercent(1e200, toFixnum(makeBignum("1e200"))) < 1e-10); assertTrue(diffPercent(-1e200, toFixnum(makeBignum("-1e200"))) < 1e-10); }, 'rationals': function() { assertEquals(0, toFixnum(zero)); assertEquals(17/2, toFixnum(makeRational(17, 2))); assertEquals(1926/3, toFixnum(makeRational(1926, 3))); assertEquals(-11150/17, toFixnum(makeRational(-11150, 17))); }, 'floats': function() { assertEquals(12345.6789, toFixnum(makeFloat(12345.6789))); assertEquals(Math.PI, toFixnum(pi)); assertEquals(Math.E, toFixnum(e)); assertEquals(Number.POSITIVE_INFINITY, toFixnum(inf)); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(negative_inf)); assertTrue(isNaN(toFixnum(nan))); }, 'complex': function() { assertFails(function() { toFixnum(makeComplex(2, 1)); }); assertFails(function() { toFixnum(i); }); assertFails(function() { toFixnum(negative_i); }); assertEquals(2, toFixnum(makeComplex(2, 0))); assertEquals(1/2, toFixnum(makeComplex(makeRational(1, 2), 0))); assertEquals(Number.POSITIVE_INFINITY, toFixnum(makeComplex(inf, 0))); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(makeComplex(negative_inf, 0))); assertTrue(isNaN(toFixnum(makeComplex(nan, 0)))); } }); describe('toExact', { 'fixnums': function() { assertEquals(1792, toExact(1792)); assertEquals(0, toExact(0)); assertEquals(-1, toExact(-1)); }, 'bignums': function() { assertEquals(makeBignum("4.2e100"), toExact(makeBignum("4.2e100"))); assertEquals(makeBignum("0"), toExact(makeBignum("0"))); assertEquals(makeBignum("1"), toExact(makeBignum("1"))); assertEquals(makeBignum("-1"), toExact(makeBignum("-1"))); assertEquals(makeBignum("-12345"), toExact(makeBignum("-12345"))); assertEquals(makeBignum("-1.723e500"), toExact(makeBignum("-1.723e500"))); }, 'rationals': function() { assertEquals(makeRational(1, 2), toExact(makeRational(1, 2))); assertEquals(makeRational(1, 9999), toExact(makeRational(1, 9999))); assertEquals(makeRational(0, 1), toExact(makeRational(0, 9999))); assertEquals(makeRational(-290, 1), toExact(makeRational(-290, 1))); }, 'floats': function() { assertEquals(makeRational(1, 2), toExact(makeFloat(0.5))); assertEquals(makeRational(1, 10), toExact(makeFloat(0.1))); assertEquals(makeRational(9, 10), toExact(makeFloat(0.9))); assertTrue(isExact(toExact(makeFloat(10234.7)))); assertTrue(diffPercent(makeRational(102347, 10), toExact(makeFloat(10234.7))) < 1); assertEquals(-1, toExact(makeFloat(-1))); assertEquals(0, toExact(makeFloat(0))); assertEquals(1024, toExact(makeFloat(1024))); assertFails(function() { toExact(nan); }); assertFails(function() { toExact(inf); }); assertFails(function() { toExact(negative_inf); }); }, 'complex': function() { assertEquals(0, toExact(makeComplex(0, 0))); assertEquals(99, toExact(makeComplex(99, 0))); assertEquals(makeRational(-1, 2), toExact(makeComplex(makeRational(-1, 2), 0))); - assertEquals(makeRational(1, 4), - toExact(makeComplex(.25, 0))); - assertFails(function() { toExact(makeComplex(nan, 0)); }); - assertFails(function() { toExact(makeComplex(inf, 0)); }); - assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); - assertFails(function() { toExact(makeComplex(0, 1)); }); - assertFails(function() { toExact(makeComplex(0, pi)); }); - assertFails(function() { toExact(makeComplex(0, e)); }); - assertFails(function() { toExact(makeComplex(0, nan)); }); + assertEquals(makeRational(1, 4), + toExact(makeComplex(makeFloat(.25), 0))); + assertFails(function() { toExact(makeComplex(nan, 0)); }); + assertFails(function() { toExact(makeComplex(inf, 0)); }); + assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); + assertTrue(eqv(toExact(makeComplex(0, 1)), makeComplex(0, 1))); + assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = subtract(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("-1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(subtract(1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532868"))); assertTrue(eqv(subtract(-1, makeBignum("3219789841236123678239865237892936825367953267523689352968869532869")), makeBignum("-3219789841236123678239865237892936825367953267523689352968869532870"))); }, 'bignum / bignum' : function() { assertTrue(eqv(subtract(makeBignum("10e500"), makeBignum("10e500")), 0)); assertFalse(eqv(subtract(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(subtract(makeBignum("0"), makeBignum("-1")), 1)); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("532679532692536916785915689")), makeBignum("235336853156840152606903617000"))); assertTrue(eqv(subtract(makeBignum("235869532689532689523689532689"), makeBignum("-532679532692536916785915689")), makeBignum("236402212222225226440475448378"))); assertTrue(eqv(subtract(makeBignum("1e500"), makeBignum("1e400")), makeBignum("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))); }, 'bignum / rational': function() { assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(1, 2)), makeRational(makeBignum("24685078656847578479654737"), 2))); assertTrue(eqv(subtract(makeBignum("12342539328423789239827369"), makeRational(makeBignum("32658963528962385326953269"), makeBignum("653289953253269"))), makeRational(makeBignum("8063256940892578770775763336720167965992"), makeBignum("653289953253269")))); }, 'bignum / float' : function() { assertTrue(eqv(subtract(makeBignum("1e50"), makeFloat(1)), makeFloat(1e50-1))); assertFalse(eqv(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(equals(subtract(makeBignum("1e50"), makeFloat(1e-50)), makeBignum("1e50"))); assertTrue(eqv(subtract(makeBignum("0"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("0")), inf)); assertTrue(eqv(subtract(makeBignum("1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("1e500")), inf)); assertTrue(eqv(subtract(makeBignum("-1e500"), inf), negative_inf)); assertTrue(eqv(subtract(inf, makeBignum("-1e500")), inf)); }, 'bignum / complex' : function() { assertTrue(eqv(0, subtract(makeBignum("42"), makeComplex(42, 0)))); assertTrue(eqv(makeComplex(-1, -4567), subtract(makeBignum("1233"), makeComplex(1234, 4567)))); assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this @@ -2636,1169 +2637,1169 @@ describe('tan', { }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); - assertEquals('-1', makeFloat(-1).toString()); + assertEquals('-1.0', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { - assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); - assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); + assertEquals("1.0+0.0i", makeComplex(1, makeFloat(0)).toString()); + assertEquals("-1.0+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); - assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); + assertEquals("0.0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(isRational(makeRational(42))); assertTrue(isRational(makeFloat(3.1415))); assertTrue(isRational(pi)); assertFalse(isRational(nan)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertTrue(! isRational("blah")); }, testNumberQuestion : function() { assertTrue(isSchemeNumber(makeRational(42))); assertTrue(isSchemeNumber(42)); assertFalse(isSchemeNumber(false)); assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ assertTrue("1" === (1).toString()); - assertEquals("5+0.0i", + assertEquals("5.0+0.0i", (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", (makeComplex(5, 1)).toString()); assertEquals("4-2i", (makeComplex(4, -2)).toString()); }, testQuotient : function(){ assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, modulo(n1, n2)); assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(isReal(pi)); assertTrue(isReal(1)); assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!isReal("hi")); }, testRound : function(){ assertTrue(equals(round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(round(makeRational(3)), makeRational(3))); assertTrue(equals(round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(round(makeRational(-17, 4)), makeRational(-4))); }, // testSgn : function(){ // assertTrue(equals(sgn(makeFloat(4)), 1)); // assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); // assertTrue(equals(sgn(0), 0)); // }, // testZero_question_ : function(){ // assertTrue(Kernel.zero_question_(0)); // assertTrue(!Kernel.zero_question_(1)); // assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); // } });
dyoo/js-numbers
a8356b226a10508e725045d9d0f8412ad87b7243
either repaired or commented tests from the old moby test suite; the ones that are commented are those that test functions that js-numbers no longer does directly.
diff --git a/test/tests.js b/test/tests.js index b0169a9..9dabbd7 100644 --- a/test/tests.js +++ b/test/tests.js @@ -3156,649 +3156,649 @@ describe('toString', { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(toExact(makeFloat(3)), makeRational(3))); assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! isExact(makeFloat(3.0))); }, // testOdd_question_ : function(){ // assertTrue(Kernel.odd_question_(1)); // assertTrue(! Kernel.odd_question_(0)); // assertTrue(Kernel.odd_question_(makeFloat(1))); // assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); // assertTrue(Kernel.odd_question_(makeRational(-1, 1))); // }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, // testEven_question_ : function(){ // assertTrue(Kernel.even_question_(0)); // assertTrue(! Kernel.even_question_(1)); // assertTrue(Kernel.even_question_(makeFloat(2))); // assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); // }, // testPositive_question_ : function(){ // assertTrue(Kernel.positive_question_(1)); // assertTrue(!Kernel.positive_question_(0)); // assertTrue(Kernel.positive_question_(makeFloat(1.1))); // assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); // }, // testNegative_question_ : function(){ // assertTrue(Kernel.negative_question_(makeRational(-5))); // assertTrue(!Kernel.negative_question_(1)); // assertTrue(!Kernel.negative_question_(0)); // assertTrue(!Kernel.negative_question_(makeFloat(1.1))); // assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); // }, testCeiling : function(){ assertTrue(equals(ceiling(1), 1)); assertTrue(equals(ceiling(pi), makeFloat(4))); assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(floor(1), 1)); assertTrue(equals(floor(pi), makeFloat(3))); assertTrue(equals(floor(makeComplex(makeFloat(3.1), makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(imaginaryPart(1), 0)); assertTrue(equals(imaginaryPart(pi), 0)); assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(realPart(1), 1)); assertTrue(equals(realPart(pi), pi)); assertTrue(equals(realPart(makeComplex(makeRational(0), makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(isInteger(1)); assertTrue(isInteger(makeFloat(3.0))); assertTrue(!isInteger(makeFloat(3.1))); assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, // testMake_dash_rectangular: function(){ // assertTrue(equals(makeComplex(1, 1), // makeComplex(makeRational(1),makeRational(1)))); // }, // testMaxAndMin : function(){ // var n1 = makeFloat(-1); // var n2 = 0; // var n3 = 1; // var n4 = makeComplex(makeRational(4),makeRational(0)); // assertTrue(equals(n4, max(n1, [n2,n3,n4]))); // assertTrue(equals(n1, min(n1, [n2,n3,n4]))); // var n5 = makeFloat(1.1); // assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); // assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); // }, testLcm : function () { assertTrue(equals(makeRational(12), lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { - assertTrue(Kernel.rational_question_(makeRational(42))); - assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); - assertTrue(! Kernel.rational_question_("blah")); + assertTrue(isRational(makeRational(42))); + assertTrue(isRational(makeFloat(3.1415))); + assertTrue(isRational(pi)); + assertFalse(isRational(nan)); + assertFalse(isRational(inf)); + assertFalse(isRational(negative_inf)); + assertTrue(! isRational("blah")); }, testNumberQuestion : function() { - assertTrue(Kernel.number_question_(makeRational(42))); - assertTrue(Kernel.number_question_(42) == false); + assertTrue(isSchemeNumber(makeRational(42))); + assertTrue(isSchemeNumber(42)); + assertFalse(isSchemeNumber(false)); + assertFalse(isSchemeNumber("blah again")); }, testNumber_dash__greaterthan_string : function(){ - assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); - assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); - - assertEquals("5+0i", - Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); - + assertTrue("1" === (1).toString()); + assertEquals("5+0.0i", + (makeComplex(5, makeFloat(0))).toString()); assertEquals("5+1i", - Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); - + (makeComplex(5, 1)).toString()); assertEquals("4-2i", - Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); - + (makeComplex(4, -2)).toString()); }, testQuotient : function(){ - assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); - assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); + assertTrue(equals(quotient(makeFloat(3), makeFloat(4)), 0)); + assertTrue(equals(quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( - Kernel.quotient(makeRational(-36), - makeRational(7)), + quotient(makeRational(-36), + makeRational(7)), makeRational(-5))); assertTrue(equals( - Kernel.quotient(makeRational(-36), - makeRational(-7)), + quotient(makeRational(-36), + makeRational(-7)), makeRational(5))); - + assertTrue(equals( - Kernel.quotient(makeRational(36), - makeRational(-7)), + quotient(makeRational(36), + makeRational(-7)), makeRational(-5))); assertTrue(equals( - Kernel.quotient(makeRational(36), - makeRational(7)), + quotient(makeRational(36), + makeRational(7)), makeRational(5))); - - - }, + testRemainder : function(){ - assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); - assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); + assertTrue(equals(remainder(makeFloat(3), makeFloat(4)), + makeFloat(3))); + assertTrue(equals(remainder(makeFloat(4), makeFloat(3)), + makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); - assertEquals(n3, Kernel.modulo(n1, n2)); - assertEquals(n2, Kernel.modulo(n2, n1)); + assertEquals(n3, modulo(n1, n2)); + assertEquals(n2, modulo(n2, n1)); assertTrue(equals( makeRational(-3), - Kernel.modulo(makeRational(13), - makeRational(-4)))); + modulo(makeRational(13), + makeRational(-4)))); assertTrue(equals( makeRational(3), - Kernel.modulo(makeRational(-13), - makeRational(4)))); + modulo(makeRational(-13), + makeRational(4)))); assertTrue(equals( makeRational(-1), - Kernel.modulo(makeRational(-13), - makeRational(-4)))); + modulo(makeRational(-13), + makeRational(-4)))); assertTrue(equals( makeRational(0), - Kernel.modulo(makeRational(4), - makeRational(-2)))); - + modulo(makeRational(4), + makeRational(-2)))); }, testReal_question_ : function(){ - assertTrue(Kernel.real_question_(pi)); - assertTrue(Kernel.real_question_(1)); - assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); - assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); - assertTrue(!Kernel.real_question_("hi")); + assertTrue(isReal(pi)); + assertTrue(isReal(1)); + assertTrue(!isReal(makeComplex(makeRational(0),makeRational(1)))); + assertTrue(isReal(makeComplex(makeRational(1),makeRational(0)))); + assertTrue(!isReal("hi")); }, testRound : function(){ - assertTrue(equals(Kernel.round(makeFloat(3.499999)), + assertTrue(equals(round(makeFloat(3.499999)), makeFloat(3))); - assertTrue(equals(Kernel.round(makeFloat(3.5)), + assertTrue(equals(round(makeFloat(3.5)), makeFloat(4))); - assertTrue(equals(Kernel.round(makeFloat(3.51)), + assertTrue(equals(round(makeFloat(3.51)), makeFloat(4))); - assertTrue(equals(Kernel.round(makeRational(3)), + assertTrue(equals(round(makeRational(3)), makeRational(3))); - assertTrue(equals(Kernel.round(makeRational(17, 4)), + assertTrue(equals(round(makeRational(17, 4)), makeRational(4))); - assertTrue(equals(Kernel.round(makeRational(-17, 4)), + assertTrue(equals(round(makeRational(-17, 4)), makeRational(-4))); }, - testSgn : function(){ - assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); - assertTrue(equals(Kernel.sgn(makeFloat(-4)), makeRational(-1))); - assertTrue(equals(Kernel.sgn(0), 0)); - }, +// testSgn : function(){ +// assertTrue(equals(sgn(makeFloat(4)), 1)); +// assertTrue(equals(sgn(makeFloat(-4)), makeRational(-1))); +// assertTrue(equals(sgn(0), 0)); +// }, - testZero_question_ : function(){ - assertTrue(Kernel.zero_question_(0)); - assertTrue(!Kernel.zero_question_(1)); - assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); - } +// testZero_question_ : function(){ +// assertTrue(Kernel.zero_question_(0)); +// assertTrue(!Kernel.zero_question_(1)); +// assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); +// } });
dyoo/js-numbers
cd6bd8a9da799388619e9eb3a15d6cdf3f002048
fixing gcd, lcm
diff --git a/src/js-numbers.js b/src/js-numbers.js index 06aae8a..d02d84f 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -157,1044 +157,1044 @@ if (typeof(exports) !== 'undefined') { return (isSchemeNumber(n) && n.isInexact()); } }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; - b = integerModulo(t, b); + b = _integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } - var divisor = gcd(result, rest[i]); + var divisor = _integerGcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { throwRuntimeError('remainder: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('remainder: the second argument ' + y.toString() + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; diff --git a/test/tests.js b/test/tests.js index 2d5d50a..b0169a9 100644 --- a/test/tests.js +++ b/test/tests.js @@ -3031,761 +3031,774 @@ describe('integerSqrt', { 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(eqv(toInexact(makeRational(3)), makeFloat(3.0))); assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { - assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), - makeRational(3) - )); - assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); + assertTrue(equals(toExact(makeFloat(3)), + makeRational(3))); + assertTrue(isExact(toExact(makeFloat(3)))); }, testFloatsAreInexact: function() { - assertTrue(! Kernel.exact_question_(makeFloat(3.0))); + assertTrue(! isExact(makeFloat(3.0))); }, - testOdd_question_ : function(){ - assertTrue(Kernel.odd_question_(1)); - assertTrue(! Kernel.odd_question_(0)); - assertTrue(Kernel.odd_question_(makeFloat(1))); - assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); - assertTrue(Kernel.odd_question_(makeRational(-1, 1))); - }, +// testOdd_question_ : function(){ +// assertTrue(Kernel.odd_question_(1)); +// assertTrue(! Kernel.odd_question_(0)); +// assertTrue(Kernel.odd_question_(makeFloat(1))); +// assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); +// assertTrue(Kernel.odd_question_(makeRational(-1, 1))); +// }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, - testEven_question_ : function(){ - assertTrue(Kernel.even_question_(0)); - assertTrue(! Kernel.even_question_(1)); - assertTrue(Kernel.even_question_(makeFloat(2))); - assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); - }, +// testEven_question_ : function(){ +// assertTrue(Kernel.even_question_(0)); +// assertTrue(! Kernel.even_question_(1)); +// assertTrue(Kernel.even_question_(makeFloat(2))); +// assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); +// }, - testPositive_question_ : function(){ - assertTrue(Kernel.positive_question_(1)); - assertTrue(!Kernel.positive_question_(0)); - assertTrue(Kernel.positive_question_(makeFloat(1.1))); - assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); - }, +// testPositive_question_ : function(){ +// assertTrue(Kernel.positive_question_(1)); +// assertTrue(!Kernel.positive_question_(0)); +// assertTrue(Kernel.positive_question_(makeFloat(1.1))); +// assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); +// }, - testNegative_question_ : function(){ - assertTrue(Kernel.negative_question_(makeRational(-5))); - assertTrue(!Kernel.negative_question_(1)); - assertTrue(!Kernel.negative_question_(0)); - assertTrue(!Kernel.negative_question_(makeFloat(1.1))); - assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); - }, +// testNegative_question_ : function(){ +// assertTrue(Kernel.negative_question_(makeRational(-5))); +// assertTrue(!Kernel.negative_question_(1)); +// assertTrue(!Kernel.negative_question_(0)); +// assertTrue(!Kernel.negative_question_(makeFloat(1.1))); +// assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); +// }, testCeiling : function(){ - assertTrue(equals(Kernel.ceiling(1), 1)); - assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); - assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); + assertTrue(equals(ceiling(1), 1)); + assertTrue(equals(ceiling(pi), makeFloat(4))); + assertTrue(equals(ceiling(makeComplex(makeFloat(3.1), + makeRational(0))), + makeFloat(4))); }, testFloor : function(){ - assertTrue(equals(Kernel.floor(1), 1)); - assertTrue(equals(Kernel.floor(pi), makeFloat(3))); - assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); + assertTrue(equals(floor(1), 1)); + assertTrue(equals(floor(pi), makeFloat(3))); + assertTrue(equals(floor(makeComplex(makeFloat(3.1), + makeRational(0))), + makeFloat(3))); }, testImag_dash_part : function(){ - assertTrue(equals(Kernel.imag_dash_part(1), 0)); - assertTrue(equals(Kernel.imag_dash_part(pi), 0)); - assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); + assertTrue(equals(imaginaryPart(1), 0)); + assertTrue(equals(imaginaryPart(pi), 0)); + assertTrue(equals(imaginaryPart(makeComplex(makeRational(0), + makeRational(1))), + 1)); }, testReal_dash_part : function(){ - assertTrue(equals(Kernel.real_dash_part(1), 1)); - assertTrue(equals(Kernel.real_dash_part(pi), pi)); - assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); + assertTrue(equals(realPart(1), 1)); + assertTrue(equals(realPart(pi), pi)); + assertTrue(equals(realPart(makeComplex(makeRational(0), + makeRational(1))), 0)); }, testInteger_question_ : function(){ - assertTrue(Kernel.integer_question_(1)); - assertTrue(Kernel.integer_question_(makeFloat(3.0))); - assertTrue(!Kernel.integer_question_(makeFloat(3.1))); - assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); - assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); + assertTrue(isInteger(1)); + assertTrue(isInteger(makeFloat(3.0))); + assertTrue(!isInteger(makeFloat(3.1))); + assertTrue(isInteger(makeComplex(makeRational(3),makeRational(0)))); + assertTrue(!isInteger(makeComplex(makeFloat(3.1),makeRational(0)))); }, - testMake_dash_rectangular: function(){ - assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); - }, +// testMake_dash_rectangular: function(){ +// assertTrue(equals(makeComplex(1, 1), +// makeComplex(makeRational(1),makeRational(1)))); +// }, - testMaxAndMin : function(){ - var n1 = makeFloat(-1); - var n2 = 0; - var n3 = 1; - var n4 = makeComplex(makeRational(4),makeRational(0)); - assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); - assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); - - var n5 = makeFloat(1.1); - assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); - assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); - }, +// testMaxAndMin : function(){ +// var n1 = makeFloat(-1); +// var n2 = 0; +// var n3 = 1; +// var n4 = makeComplex(makeRational(4),makeRational(0)); +// assertTrue(equals(n4, max(n1, [n2,n3,n4]))); +// assertTrue(equals(n1, min(n1, [n2,n3,n4]))); + +// var n5 = makeFloat(1.1); +// assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); +// assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); +// }, testLcm : function () { assertTrue(equals(makeRational(12), - Kernel.lcm(makeRational(1), - [makeRational(2), makeRational(3), makeRational(4)]))); + lcm(makeRational(1), + [makeRational(2), + makeRational(3), + makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), - Kernel.gcd(makeRational(1), - [makeRational(2), makeRational(3), makeRational(4)]))); - + gcd(makeRational(1), + [makeRational(2), + makeRational(3), + makeRational(4)]))); + assertTrue(equals(makeRational(5), - Kernel.gcd(makeRational(100), - [makeRational(5), makeRational(10), makeRational(25)]))); + gcd(makeRational(100), + [makeRational(5), + makeRational(10), + makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(pi)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_("hi")); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), makeRational(-1))); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
5af38c639b61acbf6cb64c19f46bca02a1e4d059
added isInexact, isExact
diff --git a/README b/README index bc21914..f5bd228 100644 --- a/README +++ b/README @@ -1,300 +1,306 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a toplevel namespace called jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. +isInexact: scheme-number -> boolean + Produces true if the number is inexact. + isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. +toInexact: scheme-number -> scheme-number + Converts the number to an inexact scheme-number. + add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. quotient: scheme-number scheme-number -> scheme-number Produces the quotient. Both inputs must be integers. remainder: scheme-number scheme-number -> scheme-number Produces the remainder. Both inputs must be integers. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, sgn * Bring over the numeric test cases from Moby. * Add real documentation. ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. June 2010: got implementation of integer-sqrt from Ugur Cekmez; brought in some fixes from Ethan Cecchetti. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index 47564c1..06aae8a 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,663 +1,672 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; + // isExact: scheme-number -> boolean + var isInexact = function(n) { + if (typeof(n) === 'number') { + return false; + } else { + return (isSchemeNumber(n) && n.isInexact()); + } + }; + // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; // toExact: scheme-number -> scheme-number var toInexact = function(n) { if (typeof(n) === 'number') return FloatPoint.makeInstance(n); return n.toInexact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; @@ -772,1692 +781,1709 @@ if (typeof(exports) !== 'undefined') { }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; Rational.prototype.isExact = function() { return true; }; + Rational.prototype.isInexact = function() { + return false; + }; + + Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; + FloatPoint.prototype.isExact = function() { + return false; + }; + + FloatPoint.prototype.isInexact = function() { + return true; + }; + FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.toInexact = function() { return this; }; - FloatPoint.prototype.isExact = function() { - return false; + FloatPoint.prototype.isInexact = function() { + return true; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.toInexact = function() { return Complex.makeInstance(toInexact(this.r), toInexact(this.i)); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; + Complex.prototype.isInexact = function() { + return isInexact(this.r) || isInexact(this.i); + }; + Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; @@ -3096,760 +3122,765 @@ if (typeof(exports) !== 'undefined') { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } // (public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } // (public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } // (public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } // (protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]+a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; + BigInteger.prototype.isInexact = function() { + return false; + }; + BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toInexact = function() { return FloatPoint.makeInstance(this.toFixnum()); }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; + Numbers['isInexact'] = isInexact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; })(); diff --git a/test/tests.js b/test/tests.js index b4d4e1c..2d5d50a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -255,1024 +255,1090 @@ describe('equals', { 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_false(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { assertTrue(isRational(0)); assertTrue(isRational(1)); assertTrue(isRational(238977428)); assertTrue(isRational(-2371)); }, 'bignums': function() { assertTrue(isRational(makeBignum("324987329848724791"))); assertTrue(isRational(makeBignum("0"))); assertTrue(isRational(makeBignum("-1239847210"))); }, 'rationals': function() { assertTrue(isRational(makeRational(0, 1))); assertTrue(isRational(makeRational(1, 100))); assertTrue(isRational(makeRational(9999, 10000))); assertTrue(isRational(makeRational(1, 4232))); }, 'floats': function() { assertTrue(isRational(makeFloat(1.0))); assertTrue(isRational(makeFloat(25.0))); assertTrue(isRational(e)); assertTrue(isRational(pi)); assertFalse(isRational(inf)); assertFalse(isRational(negative_inf)); assertFalse(isRational(nan)); }, 'complex': function() { assertTrue(isRational(makeComplex(0, 0))); assertTrue(isRational(makeComplex(e, 0))); assertTrue(isRational(makeComplex(pi, 0))); assertFalse(isRational(makeComplex(nan, 0))); assertFalse(isRational(makeComplex(0, 1))); assertFalse(isRational(makeComplex(0, negative_inf))); }, 'others': function() { assertFalse(isRational("0")); assertFalse(isRational("hello")); assertFalse(isRational({})); assertFalse(isRational([])); assertFalse(isRational(false)); }, }); describe('isReal', { 'fixnums': function() { assertTrue(isReal(237489)); assertTrue(isReal(0)); assertTrue(isReal(-12345)); }, 'bignums': function() { assertTrue(isReal(makeBignum("0"))); assertTrue(isReal(makeBignum("1"))); assertTrue(isReal(makeBignum("-1"))); assertTrue(isReal(makeBignum("23497842398287924789232439723"))); assertTrue(isReal(makeBignum("1e1000"))); assertTrue(isReal(makeBignum("-1e1000"))); assertTrue(isReal(makeBignum("1e23784"))); assertTrue(isReal(makeBignum("-7.241e23784"))); }, 'rationals': function() { assertTrue(isReal(makeRational(0, 1))); assertTrue(isReal(makeRational(0, 12342))); assertTrue(isReal(makeRational(-2324, 12342))); assertTrue(isReal(makeRational(1, 2))); }, 'floats': function() { assertTrue(isReal(makeFloat(1.0))); assertTrue(isReal(makeFloat(25.0))); assertTrue(isReal(e)); assertTrue(isReal(pi)); assertTrue(isReal(inf)); assertTrue(isReal(negative_inf)); assertTrue(isReal(nan)); }, 'complex': function() { assertTrue(isReal(makeComplex(0, 0))); assertTrue(isReal(makeComplex(e, 0))); assertTrue(isReal(makeComplex(pi, 0))); assertTrue(isReal(makeComplex(nan, 0))); assertTrue(isReal(makeComplex(inf, 0))); assertTrue(isReal(makeComplex(negative_inf, 0))); assertFalse(isReal(makeComplex(0, 1))); assertFalse(isReal(makeComplex(0, negative_inf))); assertFalse(isReal(makeComplex(pi, inf))); assertFalse(isReal(makeComplex(234, nan))); }, 'others': function() { assertFalse(isReal("0")); assertFalse(isReal("hello")); assertFalse(isReal([])); assertFalse(isReal({})); assertFalse(isReal(false)); } }); describe('isExact', { 'fixnums': function() { assertTrue(isExact(19)); assertTrue(isExact(0)); assertTrue(isExact(-1)); assertTrue(isExact(1)); }, 'bignums': function() { assertTrue(isExact(makeBignum("0"))); assertTrue(isExact(makeBignum("1"))); assertTrue(isExact(makeBignum("-1"))); assertTrue(isExact(makeBignum("23497842398287924789232439723"))); assertTrue(isExact(makeBignum("1e1000"))); assertTrue(isExact(makeBignum("-1e1000"))); assertTrue(isExact(makeBignum("12342357892297851728921374891327893"))); assertTrue(isExact(makeBignum("4.1321e200"))); assertTrue(isExact(makeBignum("-4.1321e200"))); }, 'rationals': function() { assertTrue(isExact(makeRational(19))); assertTrue(isExact(makeRational(0))); assertTrue(isExact(makeRational(-1))); assertTrue(isExact(makeRational(1))); assertTrue(isExact(makeRational(1, 2))); assertTrue(isExact(makeRational(1, 29291))); }, 'floats': function() { assertFalse(isExact(e)); assertFalse(isExact(pi)); assertFalse(isExact(inf)); assertFalse(isExact(negative_inf)); assertFalse(isExact(nan)); assertFalse(isExact(makeFloat(0))); assertFalse(isExact(makeFloat(1111.1))); }, 'complex': function() { assertTrue(isExact(makeComplex(0, 0))); assertTrue(isExact(makeComplex(makeRational(1,2), makeRational(1, 17)))); assertFalse(isExact(makeComplex(e, makeRational(1, 17)))); assertFalse(isExact(makeComplex(makeRational(1,2), pi))); assertFalse(isExact(makeComplex(makeRational(1,2), nan))); assertFalse(isExact(makeComplex(negative_inf, nan))); } }); + + + + +describe('isInexact', { + 'fixnums': function() { + assertFalse(isInexact(19)); + assertFalse(isInexact(0)); + assertFalse(isInexact(-1)); + assertFalse(isInexact(1)); + }, + + 'bignums': function() { + assertFalse(isInexact(makeBignum("0"))); + assertFalse(isInexact(makeBignum("1"))); + assertFalse(isInexact(makeBignum("-1"))); + assertFalse(isInexact(makeBignum("23497842398287924789232439723"))); + assertFalse(isInexact(makeBignum("1e1000"))); + assertFalse(isInexact(makeBignum("-1e1000"))); + assertFalse(isInexact(makeBignum("12342357892297851728921374891327893"))); + assertFalse(isInexact(makeBignum("4.1321e200"))); + assertFalse(isInexact(makeBignum("-4.1321e200"))); + }, + + 'rationals': function() { + assertFalse(isInexact(makeRational(19))); + assertFalse(isInexact(makeRational(0))); + assertFalse(isInexact(makeRational(-1))); + assertFalse(isInexact(makeRational(1))); + assertFalse(isInexact(makeRational(1, 2))); + assertFalse(isInexact(makeRational(1, 29291))); + }, + + 'floats': function() { + assertTrue(isInexact(e)); + assertTrue(isInexact(pi)); + assertTrue(isInexact(inf)); + assertTrue(isInexact(negative_inf)); + assertTrue(isInexact(nan)); + assertTrue(isInexact(makeFloat(0))); + assertTrue(isInexact(makeFloat(1111.1))); + }, + + 'complex': function() { + assertFalse(isInexact(makeComplex(0, 0))); + assertFalse(isInexact(makeComplex(makeRational(1,2), + makeRational(1, 17)))); + assertTrue(isInexact(makeComplex(e, + makeRational(1, 17)))); + assertTrue(isInexact(makeComplex(makeRational(1,2), + pi))); + assertTrue(isInexact(makeComplex(makeRational(1,2), + nan))); + + assertTrue(isInexact(makeComplex(negative_inf, + nan))); + } +}); + + + + + + + + describe('isInteger', { 'fixnums': function() { assertTrue(isInteger(1)); assertTrue(isInteger(-1)); }, 'bignums': function() { assertTrue(isInteger(makeBignum("2983473189472187414789132743928148151617364"))); assertTrue(isInteger(makeBignum("-99999999999999999999999999999999999999"))); }, 'rationals': function() { assertTrue(isInteger(makeRational(1, 1))); assertFalse(isInteger(makeRational(1, 2))); assertFalse(isInteger(makeRational(9999, 10000))); assertFalse(isInteger(makeRational(9999, 1000))); }, 'floats': function() { assertFalse(isInteger(makeFloat(2.3))); assertTrue(isInteger(makeFloat(4.0))); assertFalse(isInteger(inf)); assertFalse(isInteger(negative_inf)); assertFalse(isInteger(nan)); }, 'complex': function() { assertTrue(isInteger(makeComplex(42, 0))); assertFalse(isInteger(makeComplex(42, 42))); assertFalse(isInteger(i)); assertFalse(isInteger(negative_i)); }, 'others': function() { assertFalse(isInteger("hello")); assertFalse(isInteger("0")); } }); describe('toFixnum', { 'fixnums': function() { assertEquals(42, toFixnum(42)); assertEquals(-20, toFixnum(-20)); assertEquals(0, toFixnum(0)); }, 'bignums': function() { assertEquals(123456789, toFixnum(makeBignum("123456789"))); assertEquals(0, toFixnum(makeBignum("0"))); assertEquals(-123, toFixnum(makeBignum("-123"))); assertEquals(123456, toFixnum(makeBignum("123456"))); // We're dealing with big numbers, where the numerical error // makes it difficult to compare for equality. We just go for // percentage and see that it is ok. assertTrue(diffPercent(1e200, toFixnum(makeBignum("1e200"))) < 1e-10); assertTrue(diffPercent(-1e200, toFixnum(makeBignum("-1e200"))) < 1e-10); }, 'rationals': function() { assertEquals(0, toFixnum(zero)); assertEquals(17/2, toFixnum(makeRational(17, 2))); assertEquals(1926/3, toFixnum(makeRational(1926, 3))); assertEquals(-11150/17, toFixnum(makeRational(-11150, 17))); }, 'floats': function() { assertEquals(12345.6789, toFixnum(makeFloat(12345.6789))); assertEquals(Math.PI, toFixnum(pi)); assertEquals(Math.E, toFixnum(e)); assertEquals(Number.POSITIVE_INFINITY, toFixnum(inf)); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(negative_inf)); assertTrue(isNaN(toFixnum(nan))); }, 'complex': function() { assertFails(function() { toFixnum(makeComplex(2, 1)); }); assertFails(function() { toFixnum(i); }); assertFails(function() { toFixnum(negative_i); }); assertEquals(2, toFixnum(makeComplex(2, 0))); assertEquals(1/2, toFixnum(makeComplex(makeRational(1, 2), 0))); assertEquals(Number.POSITIVE_INFINITY, toFixnum(makeComplex(inf, 0))); assertEquals(Number.NEGATIVE_INFINITY, toFixnum(makeComplex(negative_inf, 0))); assertTrue(isNaN(toFixnum(makeComplex(nan, 0)))); } }); describe('toExact', { 'fixnums': function() { assertEquals(1792, toExact(1792)); assertEquals(0, toExact(0)); assertEquals(-1, toExact(-1)); }, 'bignums': function() { assertEquals(makeBignum("4.2e100"), toExact(makeBignum("4.2e100"))); assertEquals(makeBignum("0"), toExact(makeBignum("0"))); assertEquals(makeBignum("1"), toExact(makeBignum("1"))); assertEquals(makeBignum("-1"), toExact(makeBignum("-1"))); assertEquals(makeBignum("-12345"), toExact(makeBignum("-12345"))); assertEquals(makeBignum("-1.723e500"), toExact(makeBignum("-1.723e500"))); }, 'rationals': function() { assertEquals(makeRational(1, 2), toExact(makeRational(1, 2))); assertEquals(makeRational(1, 9999), toExact(makeRational(1, 9999))); assertEquals(makeRational(0, 1), toExact(makeRational(0, 9999))); assertEquals(makeRational(-290, 1), toExact(makeRational(-290, 1))); }, 'floats': function() { assertEquals(makeRational(1, 2), toExact(makeFloat(0.5))); assertEquals(makeRational(1, 10), toExact(makeFloat(0.1))); assertEquals(makeRational(9, 10), toExact(makeFloat(0.9))); assertTrue(isExact(toExact(makeFloat(10234.7)))); assertTrue(diffPercent(makeRational(102347, 10), toExact(makeFloat(10234.7))) < 1); assertEquals(-1, toExact(makeFloat(-1))); assertEquals(0, toExact(makeFloat(0))); assertEquals(1024, toExact(makeFloat(1024))); assertFails(function() { toExact(nan); }); assertFails(function() { toExact(inf); }); assertFails(function() { toExact(negative_inf); }); }, 'complex': function() { assertEquals(0, toExact(makeComplex(0, 0))); assertEquals(99, toExact(makeComplex(99, 0))); assertEquals(makeRational(-1, 2), toExact(makeComplex(makeRational(-1, 2), 0))); assertEquals(makeRational(1, 4), toExact(makeComplex(.25, 0))); assertFails(function() { toExact(makeComplex(nan, 0)); }); assertFails(function() { toExact(makeComplex(inf, 0)); }); assertFails(function() { toExact(makeComplex(negative_inf, 0)); }); assertFails(function() { toExact(makeComplex(0, 1)); }); assertFails(function() { toExact(makeComplex(0, pi)); }); assertFails(function() { toExact(makeComplex(0, e)); }); assertFails(function() { toExact(makeComplex(0, nan)); }); } }); describe('toInexact', { 'fixnum' : function() { assertTrue(eqv(toInexact(5), makeFloat(5))); assertTrue(eqv(toInexact(0), makeFloat(0))); assertTrue(eqv(toInexact(-167), makeFloat(-167))); }, 'bignum': function() { assertTrue(eqv(toInexact(makeBignum('5')), makeFloat(5))); assertTrue(eqv(toInexact(makeBignum('0')), makeFloat(0))); assertTrue(eqv(toInexact(makeBignum('-167')), makeFloat(-167))); assertTrue(eqv(toInexact(expt(2, 10000)), inf)); assertTrue(eqv(toInexact(subtract(0, expt(2, 10000))), negative_inf)); }, 'rational': function() { assertTrue(eqv(toInexact(makeRational(1, 2)), makeFloat(0.5))); assertTrue(eqv(toInexact(makeRational(12362534, 237)), makeFloat(52162.59071729958))); }, 'float': function() { assertTrue(eqv(toInexact(makeFloat(0)), toInexact(makeFloat(0)))); assertTrue(eqv(toInexact(makeFloat(123.4)), toInexact(makeFloat(123.4)))); assertTrue(eqv(toInexact(makeFloat(-42)), toInexact(makeFloat(-42)))); assertTrue(eqv(toInexact(inf), inf)); assertTrue(eqv(toInexact(negative_inf), negative_inf)); assertTrue(eqv(toInexact(negative_zero), negative_zero)); }, 'complex': function() { assertTrue(eqv(toInexact(makeComplex(1, 2)), makeComplex(makeFloat(1), makeFloat(2)))); assertTrue(eqv(toInexact(makeComplex(makeRational(1, 2), 2)), makeComplex(makeFloat(0.5), makeFloat(2)))); }}); describe('add', { 'fixnum / fixnum' : function() { assertEquals(0, add(0, 0)); assertEquals(1025, add(1024, 1)); assertEquals(-84, add(-42, -42)); assertEquals(982, add(1024, -42)); }, 'finum overflows to bignum' : function() { var aNumber = 0; for (var i = 0 ; i < 1000; i++) { aNumber = add(aNumber, fromFixnum(1e20)); } assertTrue(eqv(makeBignum("1e23"), aNumber)); }, 'fixnum / bignum': function() { assertTrue(eqv(2, add(1, makeBignum("1")))); assertTrue(eqv(makeBignum("1234298352389543294732947983"), add(1, makeBignum("1234298352389543294732947982")))); assertFalse(eqv(makeBignum("1234298352389543294732947982"), add(1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947982"), add(0, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("1234298352389543294732947981"), add(-1, makeBignum("1234298352389543294732947982")))); assertTrue(eqv(makeBignum("999999999999999999999999999999"), add(-1, makeBignum("1000000000000000000000000000000")))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("1999999999999999999999999999999"), add(makeBignum("999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(1, add(makeBignum("-999999999999999999999999999999"), makeBignum("1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1999999999999999999999999999999"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertTrue(eqv(makeBignum("-1"), add(makeBignum("999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); assertFalse(eqv(makeBignum("-20000000000000000000000000000"), add(makeBignum("-999999999999999999999999999999"), makeBignum("-1000000000000000000000000000000")))); }, 'bignum / rational': function() { assertFalse(eqv(makeBignum("1234"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1236"), add(makeBignum("1234"), makeRational(2)))); assertTrue(eqv(makeBignum("1e500"), add(makeBignum("1e500"), makeRational(0)))); assertTrue(eqv(makeRational(add(makeBignum("1e500"), 1), makeBignum("1e500")), add(1, makeRational(1, makeBignum("1e500"))))); assertTrue(eqv(fromString("461489806479620935470974478730/23987523567"), add(makeBignum("19238743223768948327"), fromString("1732914256756321/23987523567")))); assertTrue(eqv(fromString("-77100525133482588244247/239875239"), add(fromString("-321419273847891"), fromString("-13284973298/239875239")))); }, 'bignum / float' : function() { assertTrue(diffPercent(add(makeBignum("42"), makeFloat(17.5)), makeFloat(59.5)) < 2e-10); assertTrue(diffPercent(add(makeBignum("-42"), makeFloat(17.5)), makeFloat(-24.5)) < 2e-10); assertTrue(eqv(nan, add(makeBignum("0"), nan))); assertTrue(eqv(nan, add(makeBignum("10e500"), nan))); assertTrue(eqv(nan, add(makeBignum("-10e500"), nan))); assertTrue(eqv(inf, add(makeBignum("0"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("0"), negative_inf))); }, 'huge bignum and infinity': function() { // NOTE: this case is tricky, because 1e1000 will be naively coersed // to inf by toFixnum. We need to somehow distinguished coersed // values that are too large to represent with fixnums, but are yet // finite, so that addition with infinite quantities does the right // thing, at least with respect to adding bignums to inexact floats. assertTrue(eqv(negative_inf, add(makeBignum("1e1000"), negative_inf))); assertTrue(eqv(inf, add(makeBignum("-1e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("2e1000"), inf))); assertTrue(eqv(inf, add(makeBignum("-2e1000"), inf))); assertTrue(eqv(negative_inf, add(makeBignum("2e1000"), negative_inf))); assertTrue(eqv(negative_inf, add(makeBignum("-2e1000"), negative_inf))); }, 'bignum / complex' : function() { assertTrue(eqv(add(makeBignum("12345"), makeComplex(1, 1)), makeComplex(makeBignum("12346"), 1))); assertTrue(eqv(add(makeBignum("10e500"), makeComplex(makeBignum("10e500"), makeBignum("124529478"))), makeComplex(makeBignum("20e500"), makeBignum("124529478")))); }, 'fixnum / rational' : function() { assertEquals(0, add(0, makeRational(0))); assertEquals(12347, add(12345, makeRational(2))); assertEquals(makeRational(33, 2), add(16, makeRational(1, 2))); assertEquals(makeRational(-1, 2), add(0, makeRational(-1, 2))); assertEquals(makeRational(-1, 7), add(0, makeRational(-1, 7))); assertEquals(makeRational(6, 7), add(1, makeRational(-1, 7))); }, 'fixnum / floating' : function() { assertTrue(equals(0, add(0, makeFloat(0)))); assertEquals(makeFloat(1.5), add(1, makeFloat(.5))); assertEquals(makeFloat(1233.5), add(1234, makeFloat(-.5))); assertEquals(makeFloat(-1233.5), add(-1234, makeFloat(.5))); assertEquals(inf, add(1234, inf)); assertEquals(negative_inf, add(1234, negative_inf)); assertEquals(nan, add(1234, nan)); }, 'fixnum / complex' : function() { assertTrue(equals(0, add(0, makeComplex(0, 0)))); assertTrue(equals(1040, add(16, makeComplex(1024, 0)))); assertEquals(makeComplex(1040, 17), add(16, makeComplex(1024, 17))); assertEquals(makeComplex(1040, -17), add(16, makeComplex(1024, -17))); assertEquals(makeComplex(1040, pi), add(16, makeComplex(1024, pi))); }, 'rational / rational' : function() { assertEquals(1, add(makeRational(1, 2), makeRational(1, 2))); assertEquals(0, add(makeRational(1, 2), makeRational(-1, 2))); assertEquals(makeRational(155, 21), add(makeRational(17, 3), makeRational(12, 7))); assertEquals(makeRational(-1199068363, 9758), add(makeRational(-29384289, 238), makeRational(23897, 41))); assertEquals(makeRational(-1, 99990000), add(makeRational(1, 10000), makeRational(-1, 9999))); }, 'rational / floating' : function() { assertEquals(makeFloat(0.2), add(makeRational(0), makeFloat(0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(0.8), add(makeRational(1), makeFloat(-0.2))); assertEquals(makeFloat(1.1), add(makeRational(1, 2), makeFloat(0.6))); assertEquals(inf, add(makeRational(1, 2), inf)); assertEquals(negative_inf, add(makeRational(1, 2), negative_inf)); assertEquals(nan, add(makeRational(1, 2), nan)); }, 'rational / complex' : function() { assertEquals(makeComplex(makeRational(-324, 23), 1), add(makeRational(-324, 23), makeComplex(0, 1))); assertEquals(makeComplex(0, -234), add(makeRational(-324, 23), makeComplex(makeRational(324, 23), -234))); }, 'floating / floating' : function() { assertEquals(makeFloat(12345.678), add(makeFloat(12345), makeFloat(.678))); assertEquals(makeFloat(-12344.322), add(makeFloat(-12345), makeFloat(.678))); assertEquals(makeFloat(Math.PI + Math.E), add(pi, e)); assertEquals(inf, add(inf, inf)); assertEquals(nan, add(inf, negative_inf)); assertEquals(nan, add(inf, nan)); assertEquals(nan, add(negative_inf, inf)); assertEquals(negative_inf, add(negative_inf, negative_inf)); assertEquals(nan, add(negative_inf, nan)); assertEquals(nan, add(nan, inf)); assertEquals(nan, add(nan, negative_inf)); assertEquals(nan, add(nan, nan)); }, 'floating / complex' : function() { assertEquals(makeComplex(inf, 1), add(inf, makeComplex(inf, 1))); assertEquals(makeComplex(nan, 2), add(inf, makeComplex(negative_inf, 2))); assertEquals(makeComplex(nan, 3), add(inf, makeComplex(nan, 3))); assertEquals(makeComplex(nan, 4), add(negative_inf, makeComplex(inf, 4))); assertEquals(makeComplex(negative_inf, 5), add(negative_inf, makeComplex(negative_inf, 5))); assertEquals(makeComplex(nan, 6), add(negative_inf, makeComplex(nan, 6))); assertEquals(makeComplex(nan, 7), add(nan, makeComplex(inf, 7))); assertEquals(makeComplex(nan, 8), add(nan, makeComplex(negative_inf, 8))); assertEquals(makeComplex(nan, 9), add(nan, makeComplex(nan, 9))); }, 'complex / complex' : function() { assertEquals(makeComplex(4, 6), add(makeComplex(1, 2), makeComplex(3, 4))); assertEquals(makeComplex(2, 6), add(makeComplex(-1, 2), makeComplex(3, 4))); assertEquals(makeComplex(4, -2), add(makeComplex(1, 2), makeComplex(3, -4))); assertEquals(makeComplex(pi, e), add(makeComplex(pi, 0), makeComplex(0, e))); assertEquals(makeComplex(add(pi, makeRational(-1,4)), add(makeRational(1, 2), e)), add(makeComplex(pi, makeRational(1, 2)), makeComplex(makeRational(-1, 4), e))); }, 'negative zero': function() { assertTrue(eqv(negative_zero, add(negative_zero, negative_zero))); assertFalse(eqv(negative_zero, add(makeFloat(0), negative_zero))); assertTrue(eqv(makeFloat(0), add(makeFloat(0), negative_zero))); assertFalse(eqv(negative_zero, add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeFloat(0), add(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(0, makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(makeFloat(0), makeFloat(0)), add(makeFloat(0), makeComplex(negative_zero, makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, makeFloat(0)), add(negative_zero, makeComplex(negative_zero, makeFloat(0))))); }, '0 acts as the identity': function() { assertTrue(eqv(add(0, 42), 42)); assertTrue(eqv(add(0, -42), -42)); assertTrue(eqv(add(0, makeBignum("129834789213412345678910")), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(0, makeFloat(0.12345)), makeFloat(0.12345))); assertTrue(eqv(add(0, nan), nan)); assertTrue(eqv(add(0, inf), inf)); assertTrue(eqv(add(0, negative_inf), negative_inf)); assertTrue(eqv(add(42, 0), 42)); assertTrue(eqv(add(-42, 0), -42)); assertTrue(eqv(add(makeBignum("129834789213412345678910"), 0), makeBignum("129834789213412345678910"))); assertTrue(eqv(add(makeFloat(0.12345), 0), makeFloat(0.12345))); assertTrue(eqv(add(nan, 0), nan)); assertTrue(eqv(add(inf, 0), inf)); assertTrue(eqv(add(negative_inf, 0), negative_inf)); } }); describe('subtract', { 'fixnum / fixnum' : function() { assertTrue(eqv(subtract(fromFixnum(32768), fromFixnum(32768)), fromFixnum(0))); assertTrue(eqv(subtract(10, 1), 9)); assertTrue(eqv(subtract(1, 10), -9)); assertTrue(eqv(subtract(13274, 1659), 11615)); assertTrue(eqv(subtract(-13274, 1659), -14933)); @@ -2958,769 +3024,768 @@ describe('integerSqrt', { integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { - assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), - makeFloat(3.0) - )); - assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); + assertTrue(eqv(toInexact(makeRational(3)), + makeFloat(3.0))); + assertTrue(isInexact(toInexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(pi)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_("hi")); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), makeRational(-1))); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
b3b7c4fe6befcbd2785a92282756534cb3cd7f3a
implemented toInexact
diff --git a/src/js-numbers.js b/src/js-numbers.js index 9b6c61f..47564c1 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,694 +1,703 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['jsnums']) { this['jsnums'] = {}; } __PLTNUMBERS_TOP__ = this['jsnums']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; + // toExact: scheme-number -> scheme-number + var toInexact = function(n) { + if (typeof(n) === 'number') + return FloatPoint.makeInstance(n); + return n.toInexact(); + }; + + + ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (Complex.makeInstance(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { throwRuntimeError('quotient: the first argument ' + x.toString() + " is not an integer.", x); } if (! isInteger(y)) { throwRuntimeError('quotient: the second argument ' + y.toString() + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { @@ -754,1681 +763,1696 @@ if (typeof(exports) !== 'undefined') { // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; + Rational.prototype.toInexact = function() { + return FloatPoint.makeInstance(this.toFixnum()); + }; + + Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; + FloatPoint.prototype.toInexact = function() { + return this; + }; + FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; + Complex.prototype.toInexact = function() { + return Complex.makeInstance(toInexact(this.r), + toInexact(this.i)); + }; + + Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return Rational.makeInstance(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return Complex.makeInstance(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } @@ -3076,752 +3100,756 @@ if (typeof(exports) !== 'undefined') { // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } // (public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } // (public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } // (public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } // (protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]+a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.toExact = function() { return this; }; + BigInteger.prototype.toInexact = function() { + return FloatPoint.makeInstance(this.toFixnum()); + }; + BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); return Complex.makeInstance(0, searchIter(tmpThis, tmpThis)); } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['toInexact'] = toInexact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['quotient'] = quotient; Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; })();
dyoo/js-numbers
fd0b4bf450133cd6cd4c90ea7900d38445fbf841
renaming to jsnums, for easier integration with mzscheme-vm
diff --git a/README b/README index 72d6fd6..bc21914 100644 --- a/README +++ b/README @@ -1,311 +1,300 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. -Contributors: I want to express my thanks to the following people: +Contributors: I want to thank the following people: Zhe Zhang Ethan Cecchetti Ugur Cekmez Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API -Loading js-numbers.js will define a namespace called +Loading js-numbers.js will define a toplevel namespace called - plt.lib.Numbers + jsnums which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). - - isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. +quotient: scheme-number scheme-number -> scheme-number + Produces the quotient. Both inputs must be integers. + +remainder: scheme-number scheme-number -> scheme-number + Produces the remainder. Both inputs must be integers. + sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: - atan2, cosh, sinh, makePolar, makeRectangular, quotient, remainder, - sgn + atan2, cosh, sinh, sgn * Bring over the numeric test cases from Moby. * Add real documentation. -* Integrate bignums. - - - There are two bignum libraries to look into: - - jbsn: http://www-cs-students.stanford.edu/~tjw/jsbn/ - BigInteger: http://silentmatt.com/biginteger/ -We're going to use jsbn: it looks more mature, given that it's been around -for a longer time than the BigInteger package. - - -* Find out: what is the implementation mentioned in: - -Deniz A. Gursel, Ugur Cekmez, R. Emre Basar. "Implementation of -Scheme Numeric System for JavaScript" -http://ab.org.tr/ab10/bildiri/161.pdf - -I suspect it's worldwithweb, but it's hard to find. ====================================================================== History -February 2010: initial refactoring from the moby-scheme source tree. \ No newline at end of file +February 2010: initial refactoring from the moby-scheme source tree. + +June 2010: got implementation of integer-sqrt from Ugur Cekmez; +brought in some fixes from Ethan Cecchetti. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index c4ed3c1..4950928 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,1212 +1,1212 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { - if (! this['plt']) { - this['plt'] = {}; + if (! this['jsnums']) { + this['jsnums'] = {}; } - - if (! this['plt']['lib']) { - this['plt']['lib'] = {}; - } - - if (! this['plt']['lib']['Numbers']) { - this['plt']['lib']['Numbers'] = {}; - } - __PLTNUMBERS_TOP__ = this['plt']['lib']['Numbers']; + __PLTNUMBERS_TOP__ = this['jsnums']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeComplex(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { + throwRuntimeError('quotient: the first argument ' + x.toString() + + " is not an integer.", x); } if (! isInteger(y)) { + throwRuntimeError('quotient: the second argument ' + y.toString() + + " is not an integer.", y); } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { + throwRuntimeError('remainder: the first argument ' + x.toString() + + " is not an integer.", x); } if (! isInteger(y)) { + throwRuntimeError('remainder: the second argument ' + y.toString() + + " is not an integer.", y); } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && diff --git a/test/tests.js b/test/tests.js index 4fb6c95..9b7b701 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,515 +1,515 @@ // Let's open up plt.lib.Numbers to make it easy to test. -var N = plt.lib.Numbers; +var N = jsnums; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal).should_be_false(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); describe('complex construction', { 'polar' : function() { // FIXME: add tests for polar construction }, 'non-real inputs should raise errors' : function() { // FIXME: add tests for polar construction }}); describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, @@ -1515,1034 +1515,1035 @@ describe('multiply', { multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { assertTrue(eqv(sqrt(4), 2)); assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); - assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); assertTrue(eqv(sqrt(-297354289), makeComplex(0, makeFloat(17243.963842458033)))); }, + 'bignums': function() { // FIXME: we're missing this }, + 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); @@ -3027,644 +3028,642 @@ describe('toString', { assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0) )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { - assertTrue(Kernel.number_question_(plt.types.makeRational(42))); + assertTrue(Kernel.number_question_(makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(pi)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); - assertTrue(!Kernel.real_question_(plt.types.Empty.EMPTY)); - assertTrue(!Kernel.real_question_(String.makeInstance("hi"))); - assertTrue(!Kernel.real_question_(Symbol.makeInstance('h'))); + assertTrue(!Kernel.real_question_("hi")); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); - assertTrue(equals(Kernel.sgn(makeFloat(-4)), Rational.NEGATIVE_ONE)); + assertTrue(equals(Kernel.sgn(makeFloat(-4)), makeRational(-1))); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
11d6c99bf2ce8078bd581d9a0fcf7e83ae37d509
making sure sqrt -1 is complex
diff --git a/src/js-numbers.js b/src/js-numbers.js index 23994f9..c4ed3c1 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,1817 +1,1817 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['plt']) { this['plt'] = {}; } if (! this['plt']['lib']) { this['plt']['lib'] = {}; } if (! this['plt']['lib']['Numbers']) { this['plt']['lib']['Numbers'] = {}; } __PLTNUMBERS_TOP__ = this['plt']['lib']['Numbers']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); if (isReal(y) && lessThan(y, 0)) { return _expt(divide(1, x), negate(y)); } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { - return (makeBignum(n)).sqrt(); + return (makeComplex(0, sqrt(-n))); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { - var result = sqrt(x); + var result = sqrt(this); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ diff --git a/test/tests.js b/test/tests.js index f49c466..4fb6c95 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1513,1035 +1513,1045 @@ describe('multiply', { multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); assertTrue(eqv(expt(2, 1), 2)); assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); assertTrue(eqv(expt(2, -1), makeRational(1,2))); assertTrue(eqv(expt(2, -2), makeRational(1,4))); assertTrue(eqv(expt(2, -100), makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { assertTrue(eqv(expt(1, makeBignum("123689321689125689")), 1)); assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), 1)); }, 'bignum / bignum' : function() { assertTrue(eqv(expt(makeBignum("0"), makeBignum("0")), 1)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("999")), makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("1")), -2)); assertTrue(eqv(expt(makeBignum("-2"), makeBignum("2")), 4)); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-1")), makeRational(1, 2))); assertTrue(eqv(expt(makeBignum("2"), makeBignum("-999")), makeRational(1, makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { - // FIXME: we're missing this + assertTrue(eqv(sqrt(4), 2)); + assertTrue(eqv(sqrt(-4), makeComplex(0, 2))); + + assertTrue(eqv(sqrt(-1), makeComplex(0, 1))); + assertTrue(eqv(sqrt(297354289), makeFloat(17243.963842458033))); + assertTrue(eqv(sqrt(-297354289), + makeComplex(0, + makeFloat(17243.963842458033)))); }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, + 'floats': function() { - // FIXME: we're missing this + assertTrue(eqv(sqrt(makeFloat(-4)), makeComplex(0, makeFloat(2)))); + assertTrue(eqv(sqrt(makeFloat(4)), makeFloat(2))); }, + 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this
dyoo/js-numbers
28438118b3bb9ab3f55698562d904f7eb6f6ed1e
changing the logic of expt
diff --git a/src/js-numbers.js b/src/js-numbers.js index 656ed8d..23994f9 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,916 +1,914 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['plt']) { this['plt'] = {}; } if (! this['plt']['lib']) { this['plt']['lib'] = {}; } if (! this['plt']['lib']['Numbers']) { this['plt']['lib']['Numbers'] = {}; } __PLTNUMBERS_TOP__ = this['plt']['lib']['Numbers']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ - if (y > 0) { - var pow = Math.pow(x, y); - if (isOverflow(pow)) { - return (makeBignum(x)).expt(makeBignum(y)); - } else { - return pow; - } + var pow = Math.pow(x, y); + if (isOverflow(pow)) { + return (makeBignum(x)).expt(makeBignum(y)); } else { - return expt(makeRational(1, x), - negate(y)); + return pow; } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); + if (isReal(y) && lessThan(y, 0)) { + return _expt(divide(1, x), negate(y)); + } return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; @@ -942,1061 +940,1048 @@ if (typeof(exports) !== 'undefined') { }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); var _integerRemainder = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnRemainder.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; - var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; - // _rationalCache = {}; - // (function() { - // var i; - // for(i = -500; i < 500; i++) { - // _rationalCache[i] = new Rational(i, 1); - // } - // })(); - // Rational.NEGATIVE_ONE = new Rational(-1, 1); - // Rational.ZERO = new Rational(0, 1); - // Rational.ONE = new Rational(1, 1); - // Rational.TWO = new Rational(2, 1); - // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal())
dyoo/js-numbers
744363e563bb37e9988e4a5d6cd187b278abdf9d
Isolating another problem with expt and negative numbers.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 9843b94..656ed8d 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,910 +1,911 @@ // Scheme numbers. var __PLTNUMBERS_TOP__; if (typeof(exports) !== 'undefined') { __PLTNUMBERS_TOP__ = exports; } else { if (! this['plt']) { this['plt'] = {}; } if (! this['plt']['lib']) { this['plt']['lib'] = {}; } if (! this['plt']['lib']['Numbers']) { this['plt']['lib']['Numbers'] = {}; } __PLTNUMBERS_TOP__ = this['plt']['lib']['Numbers']; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ if (y > 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { - return (makeBignum(x)).expt(makeBignum(y)); + return expt(makeRational(1, x), + negate(y)); } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { - return x.expt(y); + return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; var quotient = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerQuotient(x, y); }; var remainder = function(x, y) { if (! isInteger(x)) { } if (! isInteger(y)) { } return _integerRemainder(x, y); }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return Complex.makeInstance(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); diff --git a/test/tests.js b/test/tests.js index 6d2e1dc..f49c466 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1319,1048 +1319,1075 @@ describe('subtract', { subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { assertTrue(eqv(expt(2, 0), 1)); - assertTrue(eqv(expt(2, 1), 2)); - assertTrue(eqv(expt(2, 100), makeBignum("1125899906842624"))); - assertTrue(eqv(expt(2, -1), - makeRational(1,2))); - assertTrue(eqv(expt(2, -2), - makeRational(1,4))); - assertTrue(eqv(expt(2, -100), - makeRational(1, makeBignum("1267650600228229401496703205376")))); - // FIXME: add test case where value needs to become a bignum. + assertTrue(eqv(expt(2, 1), 2)); + assertTrue(eqv(expt(2, 100), makeBignum("1267650600228229401496703205376"))); + assertTrue(eqv(expt(2, -1), + makeRational(1,2))); + assertTrue(eqv(expt(2, -2), + makeRational(1,4))); + assertTrue(eqv(expt(2, -100), + makeRational(1, makeBignum("1267650600228229401496703205376")))); }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { - // FIXME: we're missing this + assertTrue(eqv(expt(1, makeBignum("123689321689125689")), + 1)); + + assertTrue(eqv(expt(1, makeBignum("-123689321689125689")), + 1)); }, 'bignum / bignum' : function() { - // FIXME: we're missing this - }, + assertTrue(eqv(expt(makeBignum("0"), + makeBignum("0")), + 1)); + assertTrue(eqv(expt(makeBignum("2"), + makeBignum("999")), + makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688"))); + + + assertTrue(eqv(expt(makeBignum("-2"), + makeBignum("1")), + -2)); + + assertTrue(eqv(expt(makeBignum("-2"), + makeBignum("2")), + 4)); + + assertTrue(eqv(expt(makeBignum("2"), + makeBignum("-1")), + makeRational(1, 2))); + + assertTrue(eqv(expt(makeBignum("2"), + makeBignum("-999")), + makeRational(1, + makeBignum("5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688")))); + }, + 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this
dyoo/js-numbers
c6c56b5a17e369e93d42e46ad3a941532da50bce
adding tests that show something messed up with expt
diff --git a/src/js-numbers.js b/src/js-numbers.js index d55c7c0..9843b94 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -175,1300 +175,1326 @@ if (typeof(exports) !== 'undefined') { // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = (function() { var _expt = makeNumericBinop( function(x, y){ if (y > 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { if (equals(y, 0)) { return add(y, 1); } else { return x.expt(y); } }); return function(x, y) { if (equals(y, 0)) return add(y, 1); return _expt(x, y); }; })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; + + + var quotient = function(x, y) { + if (! isInteger(x)) { + } + if (! isInteger(y)) { + } + return _integerQuotient(x, y); + }; + + + var remainder = function(x, y) { + if (! isInteger(x)) { + } + if (! isInteger(y)) { + } + return _integerRemainder(x, y); + }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } - return makeComplex(multiply(r, cos(theta)), - multiply(r, sin(theta))); + return Complex.makeInstance(multiply(r, cos(theta)), + multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); + var _integerRemainder = makeIntegerBinop( + function(m, n) { + return m % n; + }, + function(m, n) { + return bnRemainder.call(m, n); + }); + // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // _rationalCache = {}; // (function() { // var i; // for(i = -500; i < 500; i++) { // _rationalCache[i] = new Rational(i, 1); // } // })(); // Rational.NEGATIVE_ONE = new Rational(-1, 1); // Rational.ZERO = new Rational(0, 1); // Rational.ONE = new Rational(1, 1); // Rational.TWO = new Rational(2, 1); // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); @@ -1722,1032 +1748,1032 @@ if (typeof(exports) !== 'undefined') { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { - return makeRational(fromString(aMatch[1]), - fromString(aMatch[2])); + return Rational.makeInstance(fromString(aMatch[1]), + fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { - return makeComplex(fromString(cMatch[1] || "0"), - fromString(cMatch[2] + (cMatch[3] || "1"))); + return Complex.makeInstance(fromString(cMatch[1] || "0"), + fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } @@ -3144,670 +3170,671 @@ if (typeof(exports) !== 'undefined') { function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; (function() { // Classic implementation of Newton-Ralphson square-root search, // adapted for integer-sqrt. // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number var searchIter = function(n, guess) { while(!(goodEnough(n, guess))) { guess = average(guess, floor(divide(n, guess))); } return guess; }; var average = function (x,y) { return floor(divide(add(x,y), 2)); }; var goodEnough = function(n, guess) { return (lessThanOrEqual(sqr(guess),n) && lessThan(n,sqr(add(guess, 1)))); }; // integerSqrt: -> scheme-number BigInteger.prototype.integerSqrt = function() { if(this.s == 0) { return searchIter(this, this); } else { var tmpThis = multiply(this, -1); - return makeComplex(0, - searchIter(tmpThis, tmpThis)); + return Complex.makeInstance(0, + searchIter(tmpThis, tmpThis)); } }; })(); // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. BigInteger.prototype.expt = function(n) { return bnPow.call(this, n); }; // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; + Numbers['quotient'] = quotient; + Numbers['remainder'] = remainder; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; - })(); diff --git a/test/tests.js b/test/tests.js index 418f883..6d2e1dc 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1318,1024 +1318,1033 @@ describe('subtract', { assertTrue(eqv(makeComplex(-1, 4567), subtract(makeBignum("1233"), makeComplex(1234, -4567)))); }, 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { + assertTrue(eqv(expt(2, 0), 1)); + assertTrue(eqv(expt(2, 1), 2)); + assertTrue(eqv(expt(2, 100), makeBignum("1125899906842624"))); + assertTrue(eqv(expt(2, -1), + makeRational(1,2))); + assertTrue(eqv(expt(2, -2), + makeRational(1,4))); + assertTrue(eqv(expt(2, -100), + makeRational(1, makeBignum("1267650600228229401496703205376")))); // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { assertTrue(eqv(expt(2, 1000), makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(0, -1)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(1, 1)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(100000001, 3)))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this
dyoo/js-numbers
e84668bd1502b7c72104d6914a707eaa91cca49e
Adding reference to Ugur
diff --git a/README b/README index 1a8744e..72d6fd6 100644 --- a/README +++ b/README @@ -1,308 +1,311 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. -Contributors: +Contributors: I want to express my thanks to the following people: + Zhe Zhang Ethan Cecchetti + Ugur Cekmez + Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a namespace called plt.lib.Numbers which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. makeComplexPolar: scheme-number scheme-number -> scheme-number Constructs a complex number; the radius and theta must be basic scheme numbers (i.e. not complex). isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. cosh: scheme-number -> scheme-number Produces the hyperbolic cosine. sinh: scheme-number -> scheme-number Produces the hyperbolic sine. realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, makePolar, makeRectangular, quotient, remainder, sgn * Bring over the numeric test cases from Moby. * Add real documentation. * Integrate bignums. - There are two bignum libraries to look into: jbsn: http://www-cs-students.stanford.edu/~tjw/jsbn/ BigInteger: http://silentmatt.com/biginteger/ We're going to use jsbn: it looks more mature, given that it's been around for a longer time than the BigInteger package. * Find out: what is the implementation mentioned in: Deniz A. Gursel, Ugur Cekmez, R. Emre Basar. "Implementation of Scheme Numeric System for JavaScript" http://ab.org.tr/ab10/bildiri/161.pdf I suspect it's worldwithweb, but it's hard to find. ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. \ No newline at end of file
dyoo/js-numbers
4210e3374fc58b116b92f608458bf8208f7fdf45
Implementation of expt for bignums
diff --git a/src/js-numbers.js b/src/js-numbers.js index f769856..013b765 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,902 +1,912 @@ // Scheme numbers. if (! this['plt']) { this['plt'] = {}; } if (! this['plt']['lib']) { this['plt']['lib'] = {}; } if (! this['plt']['lib']['Numbers']) { this['plt']['lib']['Numbers'] = {}; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = plt.lib.Numbers; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number - var expt = makeNumericBinop( - function(x, y){ - if (y >= 0) { - var pow = Math.pow(x, y); - if (isOverflow(pow)) { + var expt = (function() { + var _expt = makeNumericBinop( + function(x, y){ + if (y > 0) { + var pow = Math.pow(x, y); + if (isOverflow(pow)) { + return (makeBignum(x)).expt(makeBignum(y)); + } else { + return pow; + } + } else { return (makeBignum(x)).expt(makeBignum(y)); + } + }, + function(x, y) { + if (equals(y, 0)) { + return add(y, 1); } else { - return pow; + return x.expt(y); } - } else { - return (makeBignum(x)).expt(makeBignum(y)); - } - }, - function(x, y) { - return x.expt(y); - }); - + }); + return function(x, y) { + if (equals(y, 0)) + return add(y, 1); + return _expt(x, y); + }; + })(); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { return Math.floor(Math.sqrt(x)); } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return makeComplex(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); @@ -3118,617 +3128,623 @@ if (! this['plt']['lib']['Numbers']) { } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; // integerSqrt: -> scheme-number // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. + // expt: scheme-number -> scheme-number // Produce the power to the input. + BigInteger.prototype.expt = function(n) { + return bnPow.call(this, n); + }; + + // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; })(); \ No newline at end of file diff --git a/test/tests.js b/test/tests.js index 0a06d69..49c2c48 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1322,1025 +1322,1026 @@ describe('subtract', { 'fixnum / rational' : function() { assertTrue(eqv(makeRational(1, 2), subtract(1, makeRational(1, 2)))); assertTrue(eqv(makeRational(-1, 2), subtract(1, makeRational(3, 2)))); assertTrue(eqv(makeRational(341, 20), subtract(17, makeRational(-1, 20)))); }, 'fixnum / floating' : function() { assertTrue(eqv(makeFloat(0), subtract(1, makeFloat(1.0)))); assertTrue(eqv(makeFloat(-22998.1), subtract(2398, makeFloat(25396.1)))); }, 'fixnum / complex' : function() { assertTrue(eqv(makeComplex(0, -1), subtract(0, makeComplex(0, 1)))); assertTrue(eqv(makeComplex(0, makeFloat(-1.1234)), subtract(0, makeComplex(0, makeFloat(1.1234))))); assertTrue(eqv(makeComplex(0, makeFloat(1.1234)), subtract(0, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(234, makeFloat(1.1234)), subtract(234, makeComplex(0, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(200, makeFloat(1.1234)), subtract(234, makeComplex(34, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(-24, makeFloat(1.1234)), subtract(0, makeComplex(24, makeFloat(-1.1234))))); assertTrue(eqv(makeComplex(makeRational(16, 17), makeFloat(1.1234)), subtract(1, makeComplex(makeRational(1, 17), makeFloat(-1.1234))))); }, 'rational / rational' : function() { value_of(subtract(makeRational(1, 3), makeRational(1, 2)) ).should_be(makeRational(-1, 6)); value_of(subtract(makeRational(6, 3), makeRational(0, 1)) ).should_be(makeRational(2, 1)); value_of(subtract(makeRational(6, -3), makeRational(0, 1)) ).should_be(makeRational(-2, 1)); value_of(subtract(makeRational(-1, 3), makeRational(1, -2)) ).should_be(makeRational(1, 6)); }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { - // FIXME + assertTrue(eqv(expt(2, 1000), + makeBignum("10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"))); }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('ceiling', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this
dyoo/js-numbers
ff832782e4dc947dcdbfee9e88e1cea3d18ac361
compatibility with node.js
diff --git a/src/js-numbers.js b/src/js-numbers.js index 35b418d..bd0d6de 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,552 +1,558 @@ // Scheme numbers. +var __PLTNUMBERS_TOP__; +if (typeof(exports) !== 'undefined') { + __PLTNUMBERS_TOP__ = exports; +} else { if (! this['plt']) { this['plt'] = {}; } - -if (! this['plt']['lib']) { - this['plt']['lib'] = {}; + + if (! this['plt']['lib']) { + this['plt']['lib'] = {}; + } + + if (! this['plt']['lib']['Numbers']) { + this['plt']['lib']['Numbers'] = {}; + } + __PLTNUMBERS_TOP__ = this['plt']['lib']['Numbers']; } -if (! this['plt']['lib']['Numbers']) { - this['plt']['lib']['Numbers'] = {}; -} // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation - var Numbers = plt.lib.Numbers; - + var Numbers = __PLTNUMBERS_TOP__; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); @@ -1818,1029 +1824,1029 @@ if (! this['plt']['lib']['Numbers']) { FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { if (isInteger(this)) { return integerSqrt(this.r); } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply(2, atan(divide(this, add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return makeRational(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return makeComplex(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } - if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } - else if(j_lm && (navigator.appName != "Netscape")) { + else if(j_lm && (typeof(navigator) !== 'undefined' && navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1<<i)) > 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]; } // (public) return value as byte function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
dyoo/js-numbers
d486a9cc5b70e500ccfbbaaf4a8ed62e3f0a89f9
fixing the implemementation of BigInteger.integerSqrt so it doesn't introduce the inexact zero. Also moved off the helper methods as helper functions, locally scoped for safety.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 85845e2..35b418d 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -2900,891 +2900,892 @@ if (! this['plt']['lib']['Numbers']) { if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = [], t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; this.fromString(x,256); } } // (public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = []; r[0] = this.s; var p = this.DB-(i*this.DB)%8, d, k = 0; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<<p)-1))<<(8-p); d |= this[--i]>>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } // (public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } // (public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } // (public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } // (protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]+a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return [q,r]; } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } - // (protected) - function bnpSearchIter(guess) { - while(!(this.goodEnough(guess))) { - guess = this.improve(guess); - } - return guess; - } - - // (protected) - function bnpImprove(guess) { - return this.average(guess, floor(divide(this,guess))); - } - - // (protected) - function bnpAverage(x,y) { - return floor(divide(add(x,y), makeBignum("2"))) - } - - // (protected) - function bnpGoodEnough(guess) { - return lessThanOrEqual(sqr(guess),this) && lessThan(this,sqr(add(guess, makeBignum("1")))); - } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; - BigInteger.prototype.searchIter = bnpSearchIter - BigInteger.prototype.improve = bnpImprove - BigInteger.prototype.average = bnpAverage - BigInteger.prototype.goodEnough = bnpGoodEnough // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; - // integerSqrt: -> scheme-number - BigInteger.prototype.integerSqrt = function() { - if(this.s == 0) { - return this.searchIter(this); - }else { - tmpThis = multiply(this,makeBignum("-1")); - return makeComplex(makeFloat(0), tmpThis.searchIter(tmpThis)); - } - } + + (function() { + // Classic implementation of Newton-Ralphson square-root search, + // adapted for integer-sqrt. + // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number + var searchIter = function(n, guess) { + while(!(goodEnough(n, guess))) { + guess = average(guess, floor(divide(n, guess))); + } + return guess; + }; + + var average = function (x,y) { + return floor(divide(add(x,y), 2)); + }; + + var goodEnough = function(n, guess) { + return (lessThanOrEqual(sqr(guess),n) && + lessThan(n,sqr(add(guess, 1)))); + }; + + // integerSqrt: -> scheme-number + BigInteger.prototype.integerSqrt = function() { + if(this.s == 0) { + return searchIter(this, this); + } else { + var tmpThis = multiply(this, -1); + return makeComplex(0, + searchIter(tmpThis, tmpThis)); + } + }; + })(); + + + + // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. BigInteger.prototype.floor = function() { return this; } // ceiling: -> scheme-number // Produce the ceiling. BigInteger.prototype.ceiling = function() { return this; } // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; Numbers['cosh'] = cosh; Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; })(); diff --git a/test/tests.js b/test/tests.js index 61a3720..e8e3432 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2426,1025 +2426,1025 @@ describe('atan', { describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, 'bignums': function() { assertTrue(eqv(makeComplex(0, makeBignum("1")), integerSqrt(makeBignum("-1")))); assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); assertTrue(eqv(makeComplex(0, makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); }, 'rationals': function() { assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"), makeBignum("11111111111"))))); assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"), makeBignum("1"))))); assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"), makeBignum("1"))))); }, 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); }, 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); assertFails(function() { integerSqrt(makeComplex(negative_inf, negative_inf))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), makeBignum("2")))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0))}); assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), makeBignum("200")))}); assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeComplex(0,makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeComplex(0, makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"), makeBignum("0"))))); assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"), makeBignum("0"))))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("351")), + assertTrue(eqv(makeComplex(0,makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"), makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0) )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){
dyoo/js-numbers
a5848321dec1d80a163261edf845ddce0f3bb071
establishing test cases to make sure we're not sensitive to the representation of integers.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 6f68902..85845e2 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -429,1413 +429,1408 @@ if (! this['plt']['lib']['Numbers']) { if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { return Complex.makeInstance(0, Math.floor(Math.sqrt(-x))) } else { return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return makeComplex(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { - return (m / n - m % n / n); + return ((m / n) - ((m % n) / n)); }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return subtract(quotient, 1); } else { return quotient; } }; Rational.prototype.ceiling = function() { var quotient = _integerQuotient(this.n, this.d); if (_integerLessThan(this.n, 0)) { return quotient; } else { return add(quotient, 1); } - // if(this.n.s == -1 && this.d.s == -1 || this.n.s == 0 && this.d.s == 0) { - // return add(_integerQuotient(this.n,this.d),makeBignum("1")); - // }else { - // return _integerQuotient(this.n,this.d); - // } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // _rationalCache = {}; // (function() { // var i; // for(i = -500; i < 500; i++) { // _rationalCache[i] = new Rational(i, 1); // } // })(); // Rational.NEGATIVE_ONE = new Rational(-1, 1); // Rational.ZERO = new Rational(0, 1); // Rational.ONE = new Rational(1, 1); // Rational.TWO = new Rational(2, 1); // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; diff --git a/test/tests.js b/test/tests.js index f9bac76..61a3720 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1706,1037 +1706,1073 @@ describe('lessThanOrEqual', { }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), makeBignum("-1"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), makeBignum("1"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"), makeBignum("2"))))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"), makeBignum("-2"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), makeBignum("93485783475983475983"))))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"), 3)))); assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"), 1241)))); }, 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, + 'rationals': function() { - assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); - assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); - assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); - assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); - assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); - assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); - assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); - assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"),makeBignum("93485783475983475983"))))); + assertTrue(eqv(makeBignum("0"), + ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); + assertTrue(eqv(makeBignum("0"), + ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); + assertTrue(eqv(makeBignum("1"), + ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); + assertTrue(eqv(makeBignum("1"), + ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); + assertTrue(eqv(makeBignum("2"), + ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); + assertTrue(eqv(makeBignum("-1"), + ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); + assertTrue(eqv(makeBignum("2"), + ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); + assertTrue(eqv(makeBignum("1"), + ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); + assertTrue(eqv(makeBignum("33333334"), + ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); + assertTrue(eqv(makeBignum("99481699535421"), + ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); + assertTrue(eqv(makeBignum("88104168679280445959690"), + ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"), + makeBignum("93485783475983475983"))))); + + + assertTrue(eqv(makeBignum("0"), + ceiling(makeRational(0, 1)))); + assertTrue(eqv(makeBignum("0"), + ceiling(makeRational(0, -1)))); + assertTrue(eqv(makeBignum("1"), + ceiling(makeRational(1, 2)))); + assertTrue(eqv(makeBignum("1"), + ceiling(makeRational(1, 1)))); + assertTrue(eqv(makeBignum("2"), + ceiling(makeRational(3, 2)))); + assertTrue(eqv(makeBignum("-1"), + ceiling(makeRational(-3, 2)))); + assertTrue(eqv(makeBignum("2"), + ceiling(makeRational(-3, -2)))); + assertTrue(eqv(makeBignum("33333334"), + ceiling(makeRational(100000001, 3)))); + assertTrue(eqv(makeBignum("99481699535421"), + ceiling(makeRational(makeBignum("123456789123456789"), + 1241)))); }, + + 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this },
dyoo/js-numbers
a6a9334bdda715a2d7d1d8059bf76a04cde3b1de
repairing definition of Rational.floor, which must not assume that the numerator and denominator are of bignum type.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 8284521..6f68902 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -105,1730 +105,1737 @@ if (! this['plt']['lib']['Numbers']) { } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { if(x < 0) { - return Complex.makeInstance(0,Math.floor(Math.sqrt(-x))) - }else { - return Math.floor(Math.sqrt(x)); + return Complex.makeInstance(0, + Math.floor(Math.sqrt(-x))) + } else { + return Math.floor(Math.sqrt(x)); } } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; // Implementation of the hyperbolic functions // http://en.wikipedia.org/wiki/Hyperbolic_cosine var cosh = function(x) { return divide(add(exp(x), exp(negate(x))), 2); }; var sinh = function(x) { return divide(subtract(exp(x), exp(negate(x))), 2); }; var makeComplexPolar = function(r, theta) { // special case: if theta is zero, just return // the scalar. if (equals(theta, 0)) { return r; } return makeComplex(multiply(r, cos(theta)), multiply(r, sin(theta))); }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { - return m / n; + return (m / n - m % n / n); }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { - if(this.n.s == -1 && this.d.s == -1 || this.n.s == 0 && this.d.s == 0) { - return _integerQuotient(this.n,this.d); - }else { - return subtract(_integerQuotient(this.n,this.d),makeBignum("1")); - } + var quotient = _integerQuotient(this.n, this.d); + if (_integerLessThan(this.n, 0)) { + return subtract(quotient, 1); + } else { + return quotient; + } }; Rational.prototype.ceiling = function() { - if(this.n.s == -1 && this.d.s == -1 || this.n.s == 0 && this.d.s == 0) { - return add(_integerQuotient(this.n,this.d),makeBignum("1")); - }else { - return _integerQuotient(this.n,this.d); - } - + var quotient = _integerQuotient(this.n, this.d); + if (_integerLessThan(this.n, 0)) { + return quotient; + } else { + return add(quotient, 1); + } + // if(this.n.s == -1 && this.d.s == -1 || this.n.s == 0 && this.d.s == 0) { + // return add(_integerQuotient(this.n,this.d),makeBignum("1")); + // }else { + // return _integerQuotient(this.n,this.d); + // } }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { return fastExpt(this, a); } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // _rationalCache = {}; // (function() { // var i; // for(i = -500; i < 500; i++) { // _rationalCache[i] = new Rational(i, 1); // } // })(); // Rational.NEGATIVE_ONE = new Rational(-1, 1); // Rational.ZERO = new Rational(0, 1); // Rational.ONE = new Rational(1, 1); // Rational.TWO = new Rational(2, 1); // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { if (isInteger(this)) { if(this.n >= 0) { return FloatPoint.makeInstance(floor(sqrt(this.n))); }else { return Complex.makeInstance(0, FloatPoint.makeInstance(floor(sqrt(-this.n)))) } } else { throwRuntimeError("integerSqrt: can only be applied to an integer", this); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; diff --git a/test/tests.js b/test/tests.js index c5a360a..f9bac76 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1567,1038 +1567,1075 @@ describe('divide', { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { assertEquals(0, floor(0)); assertEquals(1, floor(1)); assertEquals(-1, floor(-1)); assertEquals(1, floor(makeFloat(1.2))); assertEquals(-2, floor(makeFloat(-1.2))); assertEquals(123123123, floor(makeFloat(123123123.9))); assertEquals(-1000000000, floor(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), floor(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), floor(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), floor(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), floor(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), floor(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), floor(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), floor(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), floor(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), floor(makeBignum("-100000009000000800000")))); }, 'rationals': function() { - assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"),makeBignum("1"))))); - assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"),makeBignum("-1"))))); - assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"),makeBignum("1"))))); - assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("-3"),makeBignum("2"))))); - assertTrue(eqv(makeBignum("-2"), floor(makeRational(makeBignum("3"),makeBignum("-2"))))); - - assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("-3"),makeBignum("-2"))))); - assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); - assertTrue(eqv(makeBignum("33333333"), floor(makeRational(makeBignum("100000001"),makeBignum("3"))))); - assertTrue(eqv(makeBignum("99481699535420"), floor(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); - assertTrue(eqv(makeBignum("88104168679280445959689"), floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"),makeBignum("93485783475983475983"))))); + assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), + makeBignum("1"))))); + assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("0"), + makeBignum("-1"))))); + assertTrue(eqv(makeBignum("0"), floor(makeRational(makeBignum("1"), + makeBignum("2"))))); + assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("1"), + makeBignum("1"))))); + assertTrue(eqv(makeBignum("1"), floor(makeRational(makeBignum("3"), + makeBignum("2"))))); + assertTrue(eqv(makeBignum("-2"), + floor(makeRational(makeBignum("-3"), + makeBignum("2"))))); + assertTrue(eqv(makeBignum("-2"), + floor(makeRational(makeBignum("3"), + makeBignum("-2"))))); + + assertTrue(eqv(makeBignum("1"), + floor(makeRational(makeBignum("-3"), + makeBignum("-2"))))); + assertTrue(eqv(makeBignum("0"), + floor(makeRational(makeBignum("100000000000000000000"), + makeBignum("200000000000000000000"))))); + assertTrue(eqv(makeBignum("33333333"), + floor(makeRational(makeBignum("100000001"), + makeBignum("3"))))); + assertTrue(eqv(makeBignum("99481699535420"), + floor(makeRational(makeBignum("123456789123456789"), + makeBignum("1241"))))); + assertTrue(eqv(makeBignum("88104168679280445959689"), + floor(makeRational(makeBignum("8236487236482736823687236826582365827652875"), + makeBignum("93485783475983475983"))))); + + + assertTrue(eqv(makeBignum("0"), floor(makeRational(0, 1)))); + assertTrue(eqv(makeBignum("0"), floor(makeRational(0, -1)))); + assertTrue(eqv(makeBignum("0"), floor(makeRational(1, 2)))); + assertTrue(eqv(makeBignum("1"), floor(makeRational(1, 1)))); + assertTrue(eqv(makeBignum("1"), floor(makeRational(3, 2)))); + assertTrue(eqv(makeBignum("-2"), floor(makeRational(-3, 2)))); + assertTrue(eqv(makeBignum("-2"), floor(makeRational(3, -2)))); + assertTrue(eqv(makeBignum("1"), floor(makeRational(-3, -2)))); + assertTrue(eqv(makeBignum("33333333"), + floor(makeRational(makeBignum("100000001"), + 3)))); + assertTrue(eqv(makeBignum("99481699535420"), + floor(makeRational(makeBignum("123456789123456789"), + 1241)))); }, + + 'floats': function() { assertEquals(makeBignum("0"), floor(makeFloat(0.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.0))); assertEquals(makeBignum("-1"), floor(makeFloat(-1.0))); assertEquals(makeBignum("1"), floor(makeFloat(1.1))); assertEquals(makeBignum("1"), floor(makeFloat(1.999))); assertEquals(makeBignum("-2"), floor(makeFloat(-1.999))); assertEquals(makeBignum("123456"), floor(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234567"), floor(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234568"), floor(makeFloat(-1234567891234567.8))); assertEquals(nan, floor(nan)); assertEquals(inf, floor(inf)); assertEquals(negative_inf, floor(negative_inf)); assertEquals(negative_zero, floor(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, floor(makeComplex(nan, 0)))); assertFails(function() { floor(makeComplex(0, nan))}); assertFails(function() { floor(makeComplex(nan, 1))}); assertFails(function() { floor(makeComplex(1, nan))}); assertFails(function() { floor(makeComplex(nan, inf))}); assertFails(function() { floor(makeComplex(inf, nan))}); assertFails(function() { floor(makeComplex(negative_zero, nan))}); assertFails(function() { floor(makeComplex(nan, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { floor(makeComplex(inf,inf))}); assertFails(function() { floor(makeComplex(0,inf))}); assertTrue(eqv(inf, floor(makeComplex(inf,0)))); assertFails(function() { floor(makeComplex(negative_inf,negative_inf))}); assertFails(function() { floor(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { floor(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1102, floor(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { floor(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { floor(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), floor(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), floor(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), floor(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("0"), floor(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-2"), floor(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234567"), floor(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('ceiling', { 'fixnums': function() { assertEquals(0, ceiling(0)); assertEquals(1, ceiling(1)); assertEquals(-1, ceiling(-1)); assertEquals(2, ceiling(makeFloat(1.2))); assertEquals(-1, ceiling(makeFloat(-1.2))); assertEquals(123123124, ceiling(makeFloat(123123123.9))); assertEquals(-999999999, ceiling(makeFloat(-999999999.9))); }, 'bignums': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeBignum("0")))); assertTrue(eqv(makeBignum("1"), ceiling(makeBignum("1")))); assertTrue(eqv(makeBignum("-1"), ceiling(makeBignum("-1")))); assertTrue(eqv(makeBignum("100"), ceiling(makeBignum("100")))); assertTrue(eqv(makeBignum("-100"), ceiling(makeBignum("-100")))); assertTrue(eqv(makeBignum("10000000000"), ceiling(makeBignum("10000000000")))); assertTrue(eqv(makeBignum("-10000000000"), ceiling(makeBignum("-10000000000")))); assertTrue(eqv(makeBignum("100000000000000000000"), ceiling(makeBignum("100000000000000000000")))); assertTrue(eqv(makeBignum("-100000009000000800000"), ceiling(makeBignum("-100000009000000800000")))); }, 'rationals': function() { assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("1"))))); assertTrue(eqv(makeBignum("0"), ceiling(makeRational(makeBignum("0"),makeBignum("-1"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("1"),makeBignum("1"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeRational(makeBignum("-3"),makeBignum("2"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeRational(makeBignum("-3"),makeBignum("-2"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeRational(makeBignum("100000000000000000000"),makeBignum("200000000000000000000"))))); assertTrue(eqv(makeBignum("33333334"), ceiling(makeRational(makeBignum("100000001"),makeBignum("3"))))); assertTrue(eqv(makeBignum("99481699535421"), ceiling(makeRational(makeBignum("123456789123456789"),makeBignum("1241"))))); assertTrue(eqv(makeBignum("88104168679280445959690"), ceiling(makeRational(makeBignum("8236487236482736823687236826582365827652875"),makeBignum("93485783475983475983"))))); }, 'floats': function() { assertEquals(makeBignum("0"), ceiling(makeFloat(0.0))); assertEquals(makeBignum("1"), ceiling(makeFloat(1.0))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.0))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.1))); assertEquals(makeBignum("2"), ceiling(makeFloat(1.999))); assertEquals(makeBignum("-1"), ceiling(makeFloat(-1.999))); assertEquals(makeBignum("123457"), ceiling(makeFloat(123456.789))); assertEquals(makeBignum("1234567891234568"), ceiling(makeFloat(1234567891234567.8))); assertEquals(makeBignum("-1234567891234567"), ceiling(makeFloat(-1234567891234567.8))); assertEquals(nan, ceiling(nan)); assertEquals(inf, ceiling(inf)); assertEquals(negative_inf, ceiling(negative_inf)); assertEquals(negative_zero, ceiling(negative_zero)); }, 'complex': function() { assertTrue(eqv(nan, ceiling(makeComplex(nan, 0)))); assertFails(function() { ceiling(makeComplex(0, nan))}); assertFails(function() { ceiling(makeComplex(nan, 1))}); assertFails(function() { ceiling(makeComplex(1, nan))}); assertFails(function() { ceiling(makeComplex(nan, inf))}); assertFails(function() { ceiling(makeComplex(inf, nan))}); assertEquals(nan,floor(makeComplex(nan, negative_zero))); assertFails(function() { ceiling(makeComplex(negative_zero, nan))}); assertFails(function() { ceiling(makeComplex(nan, nan))}); assertFails(function() { ceiling(makeComplex(inf,inf))}); assertFails(function() { ceiling(makeComplex(0,inf))}); assertTrue(eqv(inf, ceiling(makeComplex(inf,0)))); assertFails(function() { ceiling(makeComplex(negative_inf,negative_inf))}); assertFails(function() { ceiling(makeComplex(makeBignum("0"),makeBignum("2")))}); assertFails(function() { ceiling(makeComplex(makeBignum("1"),makeBignum("2")))}); assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25)));
dyoo/js-numbers
66f7902890ea0a61a4945a48f66c17c9693c1a38
fixing bugs in the tests for integer-sqrt. Exposing issues with the implementation.
diff --git a/test/tests.js b/test/tests.js index d3618f3..c5a360a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2226,1104 +2226,1154 @@ describe('ceiling', { assertTrue(eqv(1103, ceiling(makeComplex(makeRational(makeBignum("9919"), makeBignum("9")), 0)))); assertFails(function() { ceiling(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); assertFails(function() { ceiling(makeComplex(makeFloat(4.25), makeRational(3,2)))}); assertTrue(eqv(makeBignum("0"), ceiling(makeComplex(makeBignum("0"), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeBignum("-1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeBignum("1"), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex(makeRational(makeBignum("1")), makeBignum("0"))))); assertTrue(eqv(makeBignum("2"), ceiling(makeComplex(makeRational(makeBignum("3"), makeBignum("2")), makeBignum("0"))))); assertTrue(eqv(makeBignum("1"), ceiling(makeComplex( makeRational(makeBignum("100000000000000000000"), makeBignum("200000000000000000000")), makeBignum("0"))))); assertTrue(eqv(makeBignum("-1"), ceiling(makeComplex(makeFloat(-1.999), makeBignum("0"))))); assertTrue(eqv(makeBignum("1234567891234568"), ceiling(makeComplex(makeFloat(1234567891234567.8), makeBignum("0"))))); } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cosh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sinh', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { + assertEquals(0, integerSqrt(0)); assertEquals(makeComplex(0,1), integerSqrt(-1)); assertEquals(makeComplex(0,11096), integerSqrt(-123123123)); assertEquals(0, integerSqrt(-0)); assertEquals(0, integerSqrt(0)); assertEquals(1, integerSqrt(1)); assertEquals(2, integerSqrt(4)); assertEquals(2, integerSqrt(5)); assertEquals(14, integerSqrt(200)); assertEquals(5000000000, integerSqrt(25000000005000000000)); }, - 'bignums': function() { - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("1")), integerSqrt(makeBignum("-1")))); - assertTrue(eqv(makeBignum("0"), integerSqrt(makeBignum("0")))); - assertTrue(eqv(makeBignum("1"), integerSqrt(makeBignum("1")))); - assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("4")))); - assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("5")))); - assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("6")))); - assertTrue(eqv(makeBignum("2"), integerSqrt(makeBignum("7")))); - assertTrue(eqv(makeBignum("8"), integerSqrt(makeBignum("70")))); - assertTrue(eqv(makeBignum("26"), integerSqrt(makeBignum("700")))); - assertTrue(eqv(makeBignum("92113"), integerSqrt(makeBignum("8484848484")))); - assertTrue(eqv(makeBignum("35136418"), integerSqrt(makeBignum("1234567891234567")))); - assertTrue(eqv(makeBignum("50000000000"), integerSqrt(makeBignum("2500000000050000000000")))); - assertTrue(eqv(makeBignum("999999999949999"), integerSqrt(makeBignum("999999999900000000000000000000")))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("92113")), integerSqrt(makeBignum("-8484848484")))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("35136418")), integerSqrt(makeBignum("-1234567891234567")))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("50000000000")), integerSqrt(makeBignum("-2500000000050000000000")))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("999999999949999")), integerSqrt(makeBignum("-999999999900000000000000000000")))); + 'bignums': function() { + assertTrue(eqv(makeComplex(0, makeBignum("1")), + integerSqrt(makeBignum("-1")))); + assertTrue(eqv(makeBignum("0"), + integerSqrt(makeBignum("0")))); + assertTrue(eqv(makeBignum("1"), + integerSqrt(makeBignum("1")))); + assertTrue(eqv(makeBignum("2"), + integerSqrt(makeBignum("4")))); + assertTrue(eqv(makeBignum("2"), + integerSqrt(makeBignum("5")))); + assertTrue(eqv(makeBignum("2"), + integerSqrt(makeBignum("6")))); + assertTrue(eqv(makeBignum("2"), + integerSqrt(makeBignum("7")))); + assertTrue(eqv(makeBignum("8"), + integerSqrt(makeBignum("70")))); + assertTrue(eqv(makeBignum("26"), + integerSqrt(makeBignum("700")))); + assertTrue(eqv(makeBignum("92113"), + integerSqrt(makeBignum("8484848484")))); + assertTrue(eqv(makeBignum("35136418"), + integerSqrt(makeBignum("1234567891234567")))); + assertTrue(eqv(makeBignum("50000000000"), + integerSqrt(makeBignum("2500000000050000000000")))); + assertTrue(eqv(makeBignum("999999999949999"), + integerSqrt(makeBignum("999999999900000000000000000000")))); + assertTrue(eqv(makeComplex(0, makeBignum("92113")), + integerSqrt(makeBignum("-8484848484")))); + assertTrue(eqv(makeComplex(0, makeBignum("35136418")), + integerSqrt(makeBignum("-1234567891234567")))); + assertTrue(eqv(makeComplex(0, makeBignum("50000000000")), + integerSqrt(makeBignum("-2500000000050000000000")))); + assertTrue(eqv(makeComplex(0, makeBignum("999999999949999")), + integerSqrt(makeBignum("-999999999900000000000000000000")))); }, + 'rationals': function() { - assertFails(function() {integerSqrt(makeRational(makeBignum("1"),makeBignum("4")))}); - assertFails(function() {integerSqrt(makeRational(makeBignum("1"),makeBignum("5")))}); - assertFails(function() {integerSqrt(makeRational(makeBignum("5"),makeBignum("2")))}); + assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("4"))) }); + assertFails(function() { integerSqrt(makeRational(makeBignum("1"),makeBignum("5"))) }); + assertFails(function() { integerSqrt(makeRational(makeBignum("5"),makeBignum("2"))) }); - assertTrue(eqv(makeBignum("0"), integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); - assertTrue(eqv(makeBignum("2"), integerSqrt(makeRational(makeBignum("55555555555"),makeBignum("11111111111"))))); - assertTrue(eqv(makeBignum("5000000000"), integerSqrt(makeRational(makeBignum("25000000005000000000"),makeBignum("1"))))); + assertTrue(eqv(makeBignum("0"), + integerSqrt(makeRational(makeBignum("0"),makeBignum("-1"))))); + assertTrue(eqv(makeBignum("2"), + integerSqrt(makeRational(makeBignum("55555555555"), + makeBignum("11111111111"))))); + assertTrue(eqv(makeBignum("5000000000"), + integerSqrt(makeRational(makeBignum("25000000005000000000"), + makeBignum("1"))))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("5000000000")), integerSqrt(makeRational(makeBignum("-25000000005000000000"),makeBignum("1"))))); + assertTrue(eqv(makeComplex(0, makeBignum("5000000000")), + integerSqrt(makeRational(makeBignum("-25000000005000000000"), + makeBignum("1"))))); }, + 'floats': function() { assertFails(function() { integerSqrt(nan) }); assertFails(function() { integerSqrt(inf) }); assertFails(function() { integerSqrt(negative_inf) }); assertFails(function() { integerSqrt(makeFloat(0.1))}); assertFails(function() { integerSqrt(makeFloat(-0.1))}); assertFails(function() { integerSqrt(makeFloat(9999999999.000001))}); assertFails(function() { integerSqrt(makeFloat(negative_zero))}); - assertTrue(eqv(makeFloat(0.0), integerSqrt(makeFloat(0.0)))); - assertTrue(eqv(makeFloat(1.0), integerSqrt(makeFloat(1.0)))); - assertTrue(eqv(makeFloat(111.0), integerSqrt(makeFloat(12345.0)))); - assertTrue(eqv(makeComplex(0, makeFloat(111)), integerSqrt(makeFloat(-12345.0)))); + assertTrue(eqv(makeFloat(0.0), + integerSqrt(makeFloat(0.0)))); + assertTrue(eqv(makeFloat(1.0), + integerSqrt(makeFloat(1.0)))); + assertTrue(eqv(makeFloat(111.0), + integerSqrt(makeFloat(12345.0)))); + assertTrue(eqv(makeComplex(0, makeFloat(111)), + integerSqrt(makeFloat(-12345.0)))); }, + 'complex': function() { assertFails(function() { integerSqrt(makeComplex(nan, 0))}); assertFails(function() { integerSqrt(makeComplex(0, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, 1))}); assertFails(function() { integerSqrt(makeComplex(1, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, inf))}); assertFails(function() { integerSqrt(makeComplex(inf, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, negative_zero))}); assertFails(function() { integerSqrt(makeComplex(negative_zero, nan))}); assertFails(function() { integerSqrt(makeComplex(nan, nan))}); assertFails(function() { integerSqrt(makeComplex(inf,inf))}); assertFails(function() { integerSqrt(makeComplex(0,inf))}); assertFails(function() { integerSqrt(makeComplex(inf,0))}); - assertFails(function() { integerSqrt(makeComplex(negative_inf,negative_inf))}); - assertFails(function() { integerSqrt(makeComplex(makeBignum("0"),makeBignum("2")))}); - assertFails(function() { integerSqrt(makeComplex(makeBignum("1"),makeBignum("2")))}); - assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),0))}); - assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"),makeBignum("9")),makeBignum("200")))}); - assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), makeRational(3,2)))}); + assertFails(function() { integerSqrt(makeComplex(negative_inf, + negative_inf))}); + assertFails(function() { integerSqrt(makeComplex(makeBignum("0"), + makeBignum("2")))}); + assertFails(function() { integerSqrt(makeComplex(makeBignum("1"), + makeBignum("2")))}); + assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), + makeBignum("9")), + 0))}); + assertFails(function() { integerSqrt(makeComplex(makeRational(makeBignum("9919"), + makeBignum("9")), + makeBignum("200")))}); + assertFails(function() { integerSqrt(makeComplex(makeFloat(4.25), + makeRational(3,2)))}); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("1")), integerSqrt(makeComplex(makeBignum("-1"),makeBignum("0"))))); - assertTrue(eqv(makeBignum("1"), integerSqrt(makeComplex(makeBignum("1"),makeBignum("0"))))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("2")), integerSqrt(makeComplex(makeBignum("-7"),makeBignum("0"))))); - assertTrue(eqv(makeBignum("351"), integerSqrt(makeComplex(makeBignum("123456"),makeBignum("0"))))); - assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("351")), integerSqrt(makeComplex(makeBignum("-123456"),makeBignum("0"))))); + assertTrue(eqv(makeComplex(0,makeBignum("1")), + integerSqrt(makeComplex(makeBignum("-1"), + makeBignum("0"))))); + assertTrue(eqv(makeBignum("1"), + integerSqrt(makeComplex(makeBignum("1"), + makeBignum("0"))))); + assertTrue(eqv(makeComplex(0, makeBignum("2")), + integerSqrt(makeComplex(makeBignum("-7"), + makeBignum("0"))))); + assertTrue(eqv(makeBignum("351"), + integerSqrt(makeComplex(makeBignum("123456"), + makeBignum("0"))))); + assertTrue(eqv(makeComplex(makeFloat(0.0),makeBignum("351")), + integerSqrt(makeComplex(makeBignum("-123456"), + makeBignum("0"))))); } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(makeComplexPolar(makeRational(5), makeRational(0)), makeComplex(makeRational(5), makeRational(0)))); var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(imaginaryPart(n), makeRational(0), delta)); assertTrue(approxEquals(realPart(n), makeRational(-5), delta)); }, testCosh : function(){ assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(isExact(makeRational(3))); assertTrue(! isExact(makeFloat(3.0))); assertTrue(! isExact(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0) )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); },
dyoo/js-numbers
d3b446357584ac7a6b2d2dae4b005c3fb2b3a005
continuing to re-instate test cases.
diff --git a/README b/README index dc91666..1a8744e 100644 --- a/README +++ b/README @@ -1,297 +1,308 @@ js-numbers: a Javascript implementation of Scheme's numeric tower Developer: Danny Yoo (dyoo@cs.wpi.edu) License: BSD Summary: js-numbers implements the "numeric tower" commonly associated with the Scheme language. The operations in this package automatically coerse between fixnums, bignums, rationals, floating point, and complex numbers. Contributors: Zhe Zhang Ethan Cecchetti Other sources: The bignum implementation (content from jsbn.js and jsbn2.js) used in js-numbers comes from Tom Wu's JSBN library at: http://www-cs-students.stanford.edu/~tjw/jsbn/ ====================================================================== WARNING WARNING This package is currently being factored out of an existing project, Moby-Scheme. As such, the code here is in major flux, and this is nowhere near ready from public consumption yet. We're still in the middle of migrating over the test cases from Moby-Scheme over to this package, and furthermore, I'm taking the time to redo some of the implementation. So this is going to be buggy for a bit. Use at your own risk. ====================================================================== Examples [fill me in] ====================================================================== API Loading js-numbers.js will define a namespace called plt.lib.Numbers which contains following constants and functions: pi: scheme-number e: scheme-number nan: scheme-number Not-A-Number inf: scheme-number infinity negative_inf: scheme-number negative infinity negative_zero: scheme-number The value -0.0. zero: scheme-number one: scheme-number negative_one: scheme-number i: scheme-number The square root of -1. negative_i: scheme-number The negative of i. fromString: string -> (scheme-number | false) Convert from a string to a scheme-number. If we find the number is malformed, returns false. fromFixnum: javascript-number -> scheme-number Convert from a javascript number to a scheme-number. makeRational: javascript-number javascript-number? -> scheme-number Low level constructor: Constructs a rational with the given numerator and denominator. If only one argument is given, assumes the denominator is 1. makeFloat: javascript-number -> scheme-number Low level constructor: constructs a floating-point number. makeBignum: string -> scheme-number Low level constructor: constructs a bignum. makeComplex: scheme-number scheme-number? -> scheme-number Constructs a complex number; the real and imaginary parts of the input must be basic scheme numbers (i.e. not complex). If only one argument is given, assumes the imaginary part is 0. +makeComplexPolar: scheme-number scheme-number -> scheme-number + Constructs a complex number; the radius and theta must be basic + scheme numbers (i.e. not complex). + + isSchemeNumber: any -> boolean Produces true if the thing is a scheme number. isRational: scheme-number -> boolean Produces true if the number is rational. isReal: scheme-number -> boolean Produces true if the number is a real. isExact: scheme-number -> boolean Produces true if the number is being represented exactly. isInteger: scheme-number -> boolean Produces true if the number is an integer. toFixnum: scheme-number -> javascript-number Produces the javascript number closest in interpretation to the given scheme-number. toExact: scheme-number -> scheme-number Converts the number to an exact scheme-number. add: scheme-number scheme-number -> scheme-number Adds the two numbers together. subtract: scheme-number scheme-number -> scheme-number Subtracts the first number from the second. mulitply: scheme-number scheme-number -> scheme-number Multiplies the two numbers together. divide: scheme-number scheme-number -> scheme-number Divides the first number by the second. equals: scheme-number scheme-number -> boolean Produces true if the two numbers are equal. eqv: scheme-number scheme-number -> boolean Produces true if the two numbers are equivalent. approxEquals: scheme-number scheme-number scheme-number -> boolean Produces true if the two numbers are approximately equal, within the bounds of the third argument. greaterThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is greater than or equal to the second. lessThanOrEqual: scheme-number scheme-number -> boolean Produces true if the first number is less than or equal to the second. greaterThan: scheme-number scheme-number -> boolean Produces true if the first number is greater than the second. lessThan: scheme-number scheme-number -> boolean Produces true if the first number is less than the second. expt: scheme-number scheme-number -> scheme-number Produces the first number exponentiated to the second number. exp: scheme-number -> scheme-number Produces e exponentiated to the given number. modulo: scheme-number scheme-number -> scheme-number Produces the modulo of the two numbers. numerator: scheme-number -> scheme-number Produces the numerator of the rational number. denominator: scheme-number -> scheme-number Produces the denominator of the rational number. sqrt: scheme-number -> scheme-number Produces the square root. abs: scheme-number -> scheme-number Produces the absolute value. floor: scheme-number -> scheme-number Produces the floor. round: scheme-number -> scheme-number Produces the number rounded to the nearest integer. ceiling: scheme-number -> scheme-number Produces the ceiling. conjugate: scheme-number -> scheme-number Produces the complex conjugate. magnitude: scheme-number -> scheme-number Produces the complex magnitude. log: scheme-number -> scheme-number Produces the natural log (base e) of the given number. angle: scheme-number -> scheme-number Produces the complex angle. cos: scheme-number -> scheme-number Produces the cosine. sin: scheme-number -> scheme-number Produces the sin. tan: scheme-number -> scheme-number Produces the tangent. asin: scheme-number -> scheme-number - Produces the arc sine; + Produces the arc sine. acos: scheme-number -> scheme-number Produces the arc cosine. atan: scheme-number -> scheme-number Produces the arc tangent. +cosh: scheme-number -> scheme-number + Produces the hyperbolic cosine. + +sinh: scheme-number -> scheme-number + Produces the hyperbolic sine. + realPart: scheme-number -> scheme-number Produces the real part of the complex number. imaginaryPart: scheme-number -> scheme-number Produces the imaginary part of the complex number. sqr: scheme-number -> scheme-number Produces the square. integerSqrt: scheme-number -> scheme-number Produces the integer square root. gcd: scheme-number [scheme-number ...] -> scheme-number Produces the greatest common divisor. lcm: scheme-number [scheme-number ...] -> scheme-number Produces the least common mulitple. ====================================================================== Test suite Open tests/index.html, which should run our test suite over all the public functions in js-numbers. If you notice a good test case is missing, please let the developer know, and we'll be happy to add it in. ====================================================================== TODO * Absorb implementations of: atan2, cosh, sinh, makePolar, makeRectangular, quotient, remainder, sgn * Bring over the numeric test cases from Moby. * Add real documentation. * Integrate bignums. - There are two bignum libraries to look into: jbsn: http://www-cs-students.stanford.edu/~tjw/jsbn/ BigInteger: http://silentmatt.com/biginteger/ We're going to use jsbn: it looks more mature, given that it's been around for a longer time than the BigInteger package. * Find out: what is the implementation mentioned in: Deniz A. Gursel, Ugur Cekmez, R. Emre Basar. "Implementation of Scheme Numeric System for JavaScript" http://ab.org.tr/ab10/bildiri/161.pdf I suspect it's worldwithweb, but it's hard to find. ====================================================================== History February 2010: initial refactoring from the moby-scheme source tree. \ No newline at end of file diff --git a/src/js-numbers.js b/src/js-numbers.js index 1f260b2..f769856 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -156,1024 +156,1049 @@ if (! this['plt']['lib']['Numbers']) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { return Math.floor(Math.sqrt(x)); } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; + // Implementation of the hyperbolic functions + // http://en.wikipedia.org/wiki/Hyperbolic_cosine + var cosh = function(x) { + return divide(add(exp(x), exp(negate(x))), + 2); + }; + + var sinh = function(x) { + return divide(subtract(exp(x), exp(negate(x))), + 2); + }; + + + + var makeComplexPolar = function(r, theta) { + // special case: if theta is zero, just return + // the scalar. + if (equals(theta, 0)) { + return r; + } + return makeComplex(multiply(r, cos(theta)), + multiply(r, sin(theta))); + }; + + ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (n instanceof Rational) { n = numerator(n); }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (m instanceof Rational) { m = numerator(m); } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); @@ -3131,576 +3156,579 @@ if (! this['plt']['lib']['Numbers']) { r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = [], n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // END OF copy-and-paste of jsbn. BigInteger.NEGATIVE_ONE = BigInteger.ONE.negate(); // Other methods we need to add for compatibilty with js-numbers numeric tower. // add is implemented above. // subtract is implemented above. // multiply is implemented above. // equals is implemented above. // abs is implemented above. // negate is defined above. // makeBignum: string -> BigInteger var makeBignum = function(s) { if (typeof(s) === 'number') { s = s + ''; } var match = s.match(bignumScientificPattern); if (match) { return new BigInteger(match[1]+match[2] + zerostring(Number(match[3]) - match[2].length), 10); } else { return new BigInteger(s, 10); } }; var zerostring = function(n) { var buf = []; for (var i = 0; i < n; i++) { buf.push('0'); } return buf.join(''); }; BigInteger.prototype.level = 0; BigInteger.prototype.liftTo = function(target) { if (target.level === 1) { return new Rational(this, 1); } if (target.level === 2) { var fixrep = this.toFixnum(); if (fixrep === Number.POSITIVE_INFINITY) return TOO_POSITIVE_TO_REPRESENT; if (fixrep === Number.NEGATIVE_INFINITY) return TOO_NEGATIVE_TO_REPRESENT; return new FloatPoint(fixrep); } if (target.level === 3) { return new Complex(this, 0); } return throwRuntimeError("invalid level for BigInteger lift", this, target); }; BigInteger.prototype.isFinite = function() { return true; }; BigInteger.prototype.isInteger = function() { return true; }; BigInteger.prototype.isRational = function() { return true; }; BigInteger.prototype.isReal = function() { return true; }; BigInteger.prototype.isExact = function() { return true; }; BigInteger.prototype.toExact = function() { return this; }; BigInteger.prototype.toFixnum = function() { var result = 0, str = this.toString(), i; if (str[0] === '-') { for (i=1; i < str.length; i++) { result = result * 10 + Number(str[i]); } return -result; } else { for (i=0; i < str.length; i++) { result = result * 10 + Number(str[i]); } return result; } }; BigInteger.prototype.greaterThan = function(other) { return this.compareTo(other) > 0; }; BigInteger.prototype.greaterThanOrEqual = function(other) { return this.compareTo(other) >= 0; }; BigInteger.prototype.lessThan = function(other) { return this.compareTo(other) < 0; }; BigInteger.prototype.lessThanOrEqual = function(other) { return this.compareTo(other) <= 0; }; // divide: scheme-number -> scheme-number // WARNING NOTE: we override the old version of divide. BigInteger.prototype.divide = function(other) { var quotientAndRemainder = bnDivideAndRemainder.call(this, other); if (quotientAndRemainder[1].compareTo(BigInteger.ZERO) === 0) { return quotientAndRemainder[0]; } else { var result = add(quotientAndRemainder[0], Rational.makeInstance(quotientAndRemainder[1], other)); return result; } }; BigInteger.prototype.numerator = function() { return this; }; BigInteger.prototype.denominator = function() { return 1; }; // integerSqrt: -> scheme-number // sqrt: -> scheme-number // http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number // Produce the square root. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. BigInteger.prototype.imaginaryPart = function() { return 0; } BigInteger.prototype.realPart = function() { return this; } // round: -> scheme-number // Round to the nearest integer. // External interface of js-numbers: Numbers['fromFixnum'] = fromFixnum; Numbers['fromString'] = fromString; Numbers['makeBignum'] = makeBignum; Numbers['makeRational'] = Rational.makeInstance; Numbers['makeFloat'] = FloatPoint.makeInstance; Numbers['makeComplex'] = Complex.makeInstance; + Numbers['makeComplexPolar'] = makeComplexPolar; Numbers['pi'] = FloatPoint.pi; Numbers['e'] = FloatPoint.e; Numbers['nan'] = FloatPoint.nan; Numbers['negative_inf'] = FloatPoint.neginf; Numbers['inf'] = FloatPoint.inf; Numbers['negative_one'] = -1; // Rational.NEGATIVE_ONE; Numbers['zero'] = 0; // Rational.ZERO; Numbers['one'] = 1; // Rational.ONE; Numbers['i'] = plusI; Numbers['negative_i'] = minusI; Numbers['negative_zero'] = NEGATIVE_ZERO; Numbers['onThrowRuntimeError'] = onThrowRuntimeError; Numbers['isSchemeNumber'] = isSchemeNumber; Numbers['isRational'] = isRational; Numbers['isReal'] = isReal; Numbers['isExact'] = isExact; Numbers['isInteger'] = isInteger; Numbers['toFixnum'] = toFixnum; Numbers['toExact'] = toExact; Numbers['add'] = add; Numbers['subtract'] = subtract; Numbers['multiply'] = multiply; Numbers['divide'] = divide; Numbers['equals'] = equals; Numbers['eqv'] = eqv; Numbers['approxEquals'] = approxEquals; Numbers['greaterThanOrEqual'] = greaterThanOrEqual; Numbers['lessThanOrEqual'] = lessThanOrEqual; Numbers['greaterThan'] = greaterThan; Numbers['lessThan'] = lessThan; Numbers['expt'] = expt; Numbers['exp'] = exp; Numbers['modulo'] = modulo; Numbers['numerator'] = numerator; Numbers['denominator'] = denominator; Numbers['integerSqrt'] = integerSqrt; Numbers['sqrt'] = sqrt; Numbers['abs'] = abs; Numbers['floor'] = floor; Numbers['ceiling'] = ceiling; Numbers['conjugate'] = conjugate; Numbers['magnitude'] = magnitude; Numbers['log'] = log; Numbers['angle'] = angle; Numbers['tan'] = tan; Numbers['atan'] = atan; Numbers['cos'] = cos; Numbers['sin'] = sin; Numbers['tan'] = tan; Numbers['acos'] = acos; Numbers['asin'] = asin; + Numbers['cosh'] = cosh; + Numbers['sinh'] = sinh; Numbers['imaginaryPart'] = imaginaryPart; Numbers['realPart'] = realPart; Numbers['round'] = round; Numbers['sqr'] = sqr; Numbers['gcd'] = gcd; Numbers['lcm'] = lcm; })(); \ No newline at end of file diff --git a/test/tests.js b/test/tests.js index 740d28f..0a06d69 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,594 +1,604 @@ // Let's open up plt.lib.Numbers to make it easy to test. var N = plt.lib.Numbers; for (val in N) { if (N.hasOwnProperty(val)) { this[val] = N[val]; } } var diffPercent = function(x, y) { if (typeof(x) === 'number') { x = fromFixnum(x); } if (typeof(y) === 'number') { y = fromFixnum(y); } return Math.abs(toFixnum(divide(subtract(x, y), y))); }; var assertTrue = function(aVal) { value_of(aVal).should_be_true(); }; var assertFalse = function(aVal) { value_of(aVal).should_be_false(); }; var assertEquals = function(expected, aVal) { value_of(aVal).should_be(expected); }; var assertFails = function(thunk) { var isFailed = false; try { thunk(); } catch (e) { isFailed = true; } value_of(isFailed).should_be_true(); }; - describe('rational constructions', { 'constructions' : function() { value_of(isSchemeNumber(makeRational(42))) .should_be_true(); value_of(isSchemeNumber(makeRational(21, 2))) .should_be_true(); value_of(isSchemeNumber(makeRational(2, 1))) .should_be_true(); value_of(isSchemeNumber(makeRational(-17, -171))) .should_be_true(); value_of(isSchemeNumber(makeRational(17, -171))) .should_be_true(); }, 'reductions' : function() { value_of(equals(makeRational(1, 2), makeRational(5, 10))) .should_be_true(); value_of(equals(makeRational(1, 2), makeRational(6, 10))); value_of(equals(makeRational(1, 2), makeRational(-1, -2))) .should_be_true(); } }); + +describe('complex construction', { + 'polar' : function() { + // FIXME: add tests for polar construction + }, + 'non-real inputs should raise errors' : function() { + // FIXME: add tests for polar construction + }}); + + + describe('built-in constants', { 'pi': function() { value_of(isSchemeNumber(pi)).should_be_true(); }, 'e': function() { value_of(isSchemeNumber(e)).should_be_true(); }, 'nan' : function() { value_of(isSchemeNumber(nan)).should_be_true(); }, 'negative_inf' : function() { value_of(isSchemeNumber(negative_inf)).should_be_true(); }, 'inf' : function() { value_of(isSchemeNumber(inf)).should_be_true(); }, 'negative_one' : function() { value_of(isSchemeNumber(negative_one)).should_be_true(); }, 'zero' : function() { value_of(isSchemeNumber(zero)).should_be_true(); }, 'one' : function() { value_of(isSchemeNumber(one)).should_be_true(); }, 'i' : function() { value_of(isSchemeNumber(i)).should_be_true(); }, 'negative_i' : function() { value_of(isSchemeNumber(negative_i)).should_be_true(); } }); describe('fromString', { 'fixnums': function() { assertEquals(43, fromString("43")); assertEquals(43, fromString("+43")); assertEquals(-43, fromString("-43")); }, 'bignums': function() { assertEquals(makeBignum("123456789012345678901234567890"), fromString("123456789012345678901234567890")); assertEquals(makeBignum("123456789012345678901234567890"), fromString("+123456789012345678901234567890")); assertEquals(makeBignum("-123456789012345678901234567890"), fromString("-123456789012345678901234567890")); }, 'rationals': function() { assertEquals(makeRational(1, 2), fromString("1/2")); assertEquals(makeRational(23,34), fromString("+23/34")); assertEquals(makeRational(-1, 2), fromString("-1/2")); assertEquals(makeRational(1234, 5678910), fromString("1234/5678910")); assertEquals(makeRational(makeBignum("99999999999999999999"), 5678910), fromString("99999999999999999999/5678910")); assertEquals(makeRational(makeBignum("-13284973298"), makeBignum("239875239")), fromString("-13284973298/239875239")); }, 'floats': function() { assertEquals(makeFloat(42.1), fromString("42.1")); assertEquals(makeFloat(0.1), fromString(".1")); assertEquals(makeFloat(0.23), fromString("0.23")); assertEquals(makeFloat(0.1), fromString("+.1")); assertEquals(makeFloat(-0.1), fromString("-.1")); assertEquals(makeFloat(-0.123423), fromString("-.123423")); assertEquals(makeFloat(123.45), fromString("123.45")); assertEquals(makeFloat(4123.423), fromString("4.123423e3")); }, 'complex': function() { assertEquals(makeComplex(0, 1), fromString("0+i")); assertEquals(makeComplex(0, 1), fromString("0+1i")); assertEquals(makeComplex(0, makeRational(23, 45)), fromString("0+23/45i")); assertEquals(makeComplex(0, makeFloat(2.5)), fromString("0+2.5i")); assertEquals(makeComplex(0, -1), fromString("0-i")); assertEquals(makeComplex(0, -1), fromString("0-1i")); assertEquals(makeComplex(0, makeRational(-29, 42)), fromString("0-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(1, makeRational(-29, 42)), fromString("1-29/42i")); assertEquals(makeComplex(makeFloat(100.5), makeRational(-29, 42)), fromString("100.5-29/42i")); assertEquals(makeComplex(0, makeFloat(-3.7)), fromString("0-3.7i")); assertEquals(makeComplex(inf, makeFloat(-3.7)), fromString("+inf.0-3.7i")); assertEquals(makeComplex(nan, makeFloat(-3.7)), fromString("+nan.0-3.7i")); assertEquals(makeComplex(negative_inf, makeFloat(-3.7)), fromString("-inf.0-3.7i")); assertEquals(makeComplex(negative_inf, negative_inf), fromString("-inf.0-inf.0i")); assertEquals(makeComplex(nan, nan), fromString("+nan.0+nan.0i")); assertEquals(makeComplex(-42, -43), fromString("-42-43i")); }, 'special constants' : function() { assertEquals(nan, fromString("+nan.0")); assertEquals(nan, fromString("-nan.0")); assertEquals(inf, fromString("+inf.0")); assertEquals(negative_inf, fromString("-inf.0")); assertTrue(fromString("-0.0") === negative_zero); }, 'malformed': function() { assertFalse(fromString("")); assertFalse(fromString(" ")); assertFalse(fromString("sdkfjls")); assertFalse(fromString("1+1k")); assertFalse(fromString("1.2.3")); assertFalse(fromString("1.2/3")); assertFalse(fromString("--1/3")); assertFalse(fromString("-1/-3")); }}); describe('fromFixnum', { 'fixnums': function() { value_of(equals(fromFixnum(42), makeRational(42))).should_be_true(); value_of(equals(fromFixnum(43), makeRational(43))).should_be_true(); value_of(equals(fromFixnum(42), makeRational(43))).should_be_false(); }, 'bignums': function() { assertEquals(makeBignum("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e100)); assertEquals(makeBignum("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), fromFixnum(10e200)); }, 'floats': function() { value_of(equals(fromFixnum(42.1), makeFloat(42.1))).should_be_true(); } }); describe('equals', { 'nan': function() { value_of(equals(nan, nan)).should_be_false(); value_of(equals(nan, 3)).should_be_false(); value_of(equals(nan, makeFloat(239843))).should_be_false(); value_of(equals(nan, makeComplex(239843, 2))).should_be_false(); }, '-0.0': function() { assertTrue(equals(negative_zero, makeFloat(0))); assertTrue(equals(negative_zero, 0)); assertTrue(equals(negative_zero, negative_zero)); assertTrue(equals(negative_zero, makeRational(0))); assertTrue(equals(negative_zero, makeRational(makeBignum("0")))); assertFalse(equals(negative_zero, 1)); }, 'fixnum / fixnum': function() { value_of(equals(42, 42)).should_be_true(); value_of(equals(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(equals(42, makeBignum("42"))); assertTrue(equals(-42, makeBignum("-42"))); assertTrue(equals(0, makeBignum("0"))); assertFalse(equals(1, makeBignum("0"))); }, 'bignum / bignum' : function() { assertTrue(equals(makeBignum("31415926"), makeBignum("31415926"))); assertFalse(equals(makeBignum("31415926"), makeBignum("271818296"))); }, 'bignum / rational': function() { assertTrue(equals(makeBignum("0"), makeRational(0))); assertTrue(equals(makeBignum("12345"), makeRational(12345))); assertTrue(equals(makeBignum("-12345"), makeRational(-12345))); assertFalse(equals(makeBignum("1"), makeRational(0))); }, 'bignum / float' : function() { assertTrue(equals(makeBignum("12345"), makeFloat(12345.0))); assertTrue(equals(makeBignum("-12345"), makeFloat(-12345.0))); assertTrue(equals(fromString("7e40"), makeFloat(7e40))); assertTrue(equals(fromString("-7e40"), makeFloat(-7e40))); }, 'bignum / complex' : function() { assertTrue(equals(makeBignum("1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertFalse(equals(makeBignum("1.1e2000"), makeComplex(makeBignum("1e2000"), 0))); assertTrue(equals(makeBignum("0"), makeComplex(0, 0))); assertTrue(equals(makeBignum("91326"), makeComplex(makeBignum("91326")))); assertFalse(equals(makeBignum("00000"), makeComplex(makeBignum("91326")))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210)))); assertTrue(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0)))); assertFalse(equals(makeBignum("90210"), makeComplex(makeFloat(90210), makeFloat(0.1)))); }, 'fixnum / rational': function() { value_of(equals(0, zero)).should_be_true(); value_of(equals(42, makeRational(84, 2))).should_be_true(); value_of(equals(42, makeRational(84, 3))).should_be_false(); value_of(equals(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(equals(1024, makeFloat(1024))).should_be_true(); value_of(equals(1024, makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex ': function() { value_of(equals(31337, makeComplex(31337))).should_be_true(); value_of(equals(31337, makeComplex(31337, 1))).should_be_false(); }, 'rational / rational ' : function() { value_of(equals(makeRational(23849), makeRational(23849))).should_be_true(); value_of(equals(makeRational(23849), makeRational(23489))).should_be_false(); }, 'rational / float': function() { value_of(equals(makeRational(2), makeFloat(2))).should_be_true(); value_of(equals(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(equals(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(equals(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(equals(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(equals(pi, pi)).should_be_true(); value_of(equals(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(equals(pi, makeComplex(pi, 0))).should_be_true(); value_of(equals(pi, makeComplex(e, 0))).should_be_false(); }, 'complex / complex': function() { value_of(equals(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(equals(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(equals(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_true(); value_of(equals(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(equals(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); } }); describe('eqv', { 'nan' : function() { value_of(eqv(nan, makeFloat(Number.NaN))).should_be_true(); }, '-0.0' : function() { assertFalse(eqv(negative_zero, makeFloat(0))); assertFalse(eqv(negative_zero, 0)); assertTrue(eqv(negative_zero, negative_zero)); assertFalse(eqv(negative_zero, makeRational(0))); assertFalse(eqv(negative_zero, makeRational(makeBignum("0")))); assertFalse(eqv(negative_zero, 1)); }, 'inf' : function() { value_of(eqv(inf, inf)).should_be_true(); value_of(eqv(negative_inf, negative_inf)).should_be_true(); assertFalse(eqv(inf, negative_inf)); assertFalse(eqv(inf, makeBignum("1e3000"))); assertFalse(eqv(negative_inf, makeBignum("-1e3000"))); }, 'fixnum / fixnum': function() { value_of(eqv(42, 42)).should_be_true(); value_of(eqv(42, 43)).should_be_false(); }, 'fixnum / bignum': function() { assertTrue(eqv(0, makeBignum("0"))); assertTrue(eqv(-1, makeBignum("-1"))); assertTrue(eqv(42, makeBignum("42"))); assertTrue(eqv(123456789, makeBignum("123456789"))); assertTrue(eqv(-123456789, makeBignum("-123456789"))); assertFalse(eqv(-123456788, makeBignum("-123456789"))); }, 'bignum / bignum' : function() { assertTrue(eqv(makeBignum("0"), makeBignum("0"))); assertTrue(eqv(makeBignum("-1"), makeBignum("-1"))); assertTrue(eqv(makeBignum("7.3241e324"), makeBignum("7.3241e324"))); assertFalse(eqv(makeBignum("7.3240e324"), makeBignum("7.3241e324"))); assertTrue(eqv(makeBignum("-13241e324"), makeBignum("-13241e324"))); assertTrue(eqv(makeBignum("3"), makeBignum("3"))); assertFalse(eqv(makeBignum("12345"), makeBignum("12344"))); }, 'bignum / rational': function() { assertTrue(eqv(makeBignum("0"), makeRational(0, 1))); assertTrue(eqv(makeBignum("0"), makeRational(makeBignum("0"), 1))); assertTrue(eqv(makeBignum("24"), makeRational(makeBignum("24"), 1))); assertTrue(eqv(makeBignum("-1"), makeRational(-1, 1))); assertFalse(eqv(makeBignum("0"), makeRational(-1, 1))); assertTrue(eqv(makeBignum("3"), makeRational(makeBignum("3")))); assertTrue(eqv(makeBignum("27"), makeRational(27))); }, 'bignum / float' : function() { assertFalse(eqv(makeBignum("27"), makeFloat(27.0))); assertFalse(eqv(makeBignum("0"), makeFloat(0))); assertFalse(eqv(makeBignum("1e100"), makeFloat(1e100))); assertFalse(eqv(makeBignum("-1e100"), makeFloat(-1e100))); }, 'bignum / complex' : function() { assertTrue(eqv(makeBignum("71"), makeComplex(71))); assertTrue(eqv(makeBignum("71"), makeComplex(makeBignum("71")))); assertTrue(eqv(makeBignum("71"), makeComplex(makeRational(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71)))); assertFalse(eqv(makeBignum("71"), makeComplex(70))); assertFalse(eqv(makeBignum("66"), makeComplex(makeBignum("42")))); assertFalse(eqv(makeBignum("71"), makeComplex(makeRational(71, 17)))); assertFalse(eqv(makeBignum("71"), makeComplex(makeFloat(71), 2))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 0))); assertTrue(eqv(makeBignum("5e23"), makeComplex(makeRational(makeBignum("5e23")), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeFloat(5e23), 0))); assertFalse(eqv(makeBignum("5e23"), makeComplex(makeBignum("5e23"), 1))); }, 'fixnum / rational': function() { value_of(eqv(42, makeRational(84, 2))).should_be_true(); value_of(eqv(42, makeRational(84, 3))).should_be_false(); value_of(eqv(28, makeRational(84, 3))).should_be_true(); }, 'fixnum / float ' : function() { value_of(eqv(fromFixnum(1024), makeFloat(1024))).should_be_false(); value_of(eqv(fromFixnum(1024), makeFloat(1024.0001))).should_be_false(); }, 'fixnum / complex' : function() { value_of(eqv(10, makeComplex(10))).should_be_true(); value_of(eqv(10, makeComplex(0))).should_be_false(); }, 'rational / rational': function() { value_of(eqv(makeRational(2, 3), makeRational(2, 3))).should_be_true(); value_of(eqv(makeRational(3, 2), makeRational(2, 3))).should_be_false(); }, 'rational / float': function() { value_of(eqv(makeRational(2), makeFloat(2))).should_be_false(); value_of(eqv(makeRational(2), makeFloat(2.1))).should_be_false(); }, 'rational / complex': function() { value_of(eqv(makeRational(2), makeComplex(2, 0))).should_be_true(); value_of(eqv(makeRational(2), makeComplex(2, 1))).should_be_false(); value_of(eqv(makeRational(2), makeComplex(0, 0))).should_be_false(); }, 'float / float': function() { value_of(eqv(pi, pi)).should_be_true(); value_of(eqv(e, e)).should_be_true(); value_of(eqv(pi, e)).should_be_false(); }, 'float / complex': function() { value_of(eqv(pi, makeComplex(pi))).should_be_true(); value_of(eqv(3, makeComplex(makeFloat(3)))).should_be_false(); value_of(eqv(pi, makeComplex(pi, 1))).should_be_false(); }, 'complex / complex': function() { value_of(eqv(makeComplex(17, 2), makeComplex(17, 2))).should_be_true(); value_of(eqv(makeComplex(17, 2), makeComplex(2, 17))).should_be_false(); value_of(eqv(makeComplex(17, 2), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(2, 17), makeComplex(17, 17))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeFloat(100), 0))).should_be_true(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100.1), 0), makeComplex(makeRational(100), 0))).should_be_false(); value_of(eqv(makeComplex(makeFloat(100), 0), makeComplex(makeRational(100), 1))).should_be_false(); }, 'tricky case with complex': function() { value_of(eqv(makeComplex(0, makeFloat(1.1)), makeComplex(makeFloat(0.0), makeFloat(1.1)))).should_be_false(); } }); describe('isSchemeNumber', { 'strings': function() { value_of(isSchemeNumber("42")).should_be_false(); value_of(isSchemeNumber(42)).should_be_true(); assertTrue(isSchemeNumber(makeBignum("298747328418794387941798324789421978"))); value_of(isSchemeNumber(makeRational(42, 42))).should_be_true(); value_of(isSchemeNumber(makeFloat(42.2))).should_be_true(); value_of(isSchemeNumber(makeComplex(17))).should_be_true(); value_of(isSchemeNumber(makeComplex(17, 1))).should_be_true(); value_of(isSchemeNumber(makeComplex(makeFloat(17), 1))).should_be_true(); value_of(isSchemeNumber(undefined)).should_be_false(); value_of(isSchemeNumber(null)).should_be_false(); value_of(isSchemeNumber(false)).should_be_false(); } }); describe('isRational', { 'fixnums': function() { @@ -1763,1475 +1773,1498 @@ describe('greaterThan', { describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'expt of anything to zero is 1' : function() { assertTrue(eqv(1, expt(nan, 0))); assertTrue(eqv(1, expt(inf, 0))); assertTrue(eqv(1, expt(negative_inf, 0))); assertTrue(eqv(1, expt(negative_zero, 0))); assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('ceiling', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); +describe('cosh', { + 'fixnums': function() { + // FIXME: we're missing this + }, + 'bignums': function() { + // FIXME: we're missing this + }, + 'rationals': function() { + // FIXME: we're missing this + }, + 'floats': function() { + // FIXME: we're missing this + }, + 'complex': function() { + // FIXME: we're missing this + } +}); + + +describe('sinh', { + 'fixnums': function() { + // FIXME: we're missing this + }, + 'bignums': function() { + // FIXME: we're missing this + }, + 'rationals': function() { + // FIXME: we're missing this + }, + 'floats': function() { + // FIXME: we're missing this + }, + 'complex': function() { + // FIXME: we're missing this + } +}); + + + + describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, integerSqrt(n1)); assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(acos(1), 0)); assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ assertTrue(equals(asin(0), 0)); assertTrue(equals(asin(-1), multiply(pi, makeRational(-1, 2)))); assertTrue(equals(asin(1), divide(pi, 2))); assertTrue(equals(asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals(asin(makeComplex(1, 5)), makeComplex(makeFloat(0.1937931365549321), makeFloat(2.3309746530493123)))); }, testTan : function(){ assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(isSchemeNumber(pi)); assertTrue(isSchemeNumber(1)); assertTrue(isSchemeNumber(makeFloat(2.718))); assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { - assertTrue(equals(Kernel.make_dash_polar(makeRational(5), - makeRational(0)), - makeComplex(makeRational(5),makeRational( 0)))); - var n = Kernel.make_dash_polar(makeRational(5), + assertTrue(equals(makeComplexPolar(makeRational(5), + makeRational(0)), + makeComplex(makeRational(5), + makeRational(0)))); + var n = makeComplexPolar(makeRational(5), pi); var delta = makeFloat(0.0000001); - assertTrue(approxEquals(Kernel.imag_dash_part(n), - makeRational(0), - delta)); - assertTrue(approxEquals(Kernel.real_dash_part(n), - makeRational(-5), - delta)); + assertTrue(approxEquals(imaginaryPart(n), + makeRational(0), + delta)); + assertTrue(approxEquals(realPart(n), + makeRational(-5), + delta)); }, - - testMakeRectangular: function() { - assertTrue(equals(Kernel.make_dash_rectangular - (makeRational(4), - makeRational(3)), - makeComplex(makeRational(4),makeRational( 3)))); - assertTrue(equals(Kernel.make_dash_rectangular - (makeRational(5), - makeRational(4)), - makeComplex(makeRational(5),makeRational( 4)))); - }, - - testCosh : function(){ - assertTrue(equals(Kernel.cosh(0), 1)); + assertTrue(equals(cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ - assertTrue(equals(Kernel.denominator(makeRational(7,2)), makeRational(2,1))); - assertTrue(equals(Kernel.denominator(makeFloat(3)), - makeFloat(1))); + assertTrue(equals(denominator(makeRational(7,2)), + makeRational(2,1))); + assertTrue(equals(denominator(makeFloat(3)), + makeFloat(1))); }, testNumerator : function(){ - assertTrue(equals(Kernel.numerator(makeRational(7,2)), makeRational(7,1))); - assertTrue(equals(Kernel.numerator(makeFloat(3)), - makeFloat(3))); + assertTrue(equals(numerator(makeRational(7,2)), + makeRational(7,1))); + assertTrue(equals(numerator(makeFloat(3)), + makeFloat(3))); }, testIsExact : function() { - assertTrue(Kernel.exact_question_(makeRational(3))); - assertTrue(! Kernel.exact_question_(makeFloat(3.0))); - assertTrue(! Kernel.exact_question_(makeFloat(3.5))); + assertTrue(isExact(makeRational(3))); + assertTrue(! isExact(makeFloat(3.0))); + assertTrue(! isExact(makeFloat(3.5))); }, - testIsInexact : function() { - assertTrue(! Kernel.inexact_question_(makeRational(3))); - assertTrue(Kernel.inexact_question_(makeFloat(3.0))); - assertTrue(Kernel.inexact_question_(makeFloat(3.5))); - }, - - testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0) )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(plt.types.makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(pi)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.real_question_(String.makeInstance("hi"))); assertTrue(!Kernel.real_question_(Symbol.makeInstance('h'))); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), Rational.NEGATIVE_ONE)); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
44cfec9a7e86b3085df091581e3f17eee0da9f1d
more tests passing.
diff --git a/src/js-numbers.js b/src/js-numbers.js index c216b16..1f260b2 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -242,1062 +242,1069 @@ if (! this['plt']['lib']['Numbers']) { function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { return Math.floor(Math.sqrt(x)); } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; // fastExpt: computes n^k by squaring. // n^k = (n^2)^(k/2) // Assumes k is non-negative integer. var fastExpt = function(n, k) { var acc = 1; while (true) { if (_integerIsZero(k)) { return acc; } if (equals(modulo(k, 2), 0)) { n = multiply(n, n); k = divide(k, 2); } else { acc = multiply(acc, n); k = subtract(k, 1); } } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { - if (m instanceof Complex) { + if (m instanceof Rational) { + m = numerator(m); + } else if (m instanceof Complex) { m = realPart(m); } - if (n instanceof Complex) { + + if (n instanceof Rational) { + n = numerator(n); + }else if (n instanceof Complex) { n = realPart(n); } if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { - if (m instanceof Complex) { + if (m instanceof Rational) { + m = numerator(m); + } else if (m instanceof Complex) { m = realPart(m); } if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { return fromFixnum(Math.floor(this.n / this.d)); }; Rational.prototype.ceiling = function() { return fromFixnum(Math.ceil(this.n / this.d)); }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ @@ -1578,1075 +1585,1068 @@ if (! this['plt']['lib']['Numbers']) { }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); - var z2 = Complex.makeInstance(0, Rational.TWO); + var z2 = Complex.makeInstance(0, 2); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt = function(y){ if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { return fastExpt(this, y); } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = - subtract( - 1, - sqr(this)); + subtract(1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); - return multiply( - Rational.TWO, - atan(divide( - this, - add( - 1, - sqrtOneNegateThisSq)))); + return multiply(2, atan(divide(this, + add(1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return makeRational(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return makeComplex(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 diff --git a/test/tests.js b/test/tests.js index a625b00..740d28f 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1360,1877 +1360,1878 @@ describe('subtract', { 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0.0), subtract(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0.0), subtract(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, subtract(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), subtract(0, makeComplex(makeFloat(0), makeFloat(0))))); }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negation': function() { assertTrue(eqv(subtract(0, 42), -42)); assertTrue(eqv(subtract(0, -42), 42)); assertTrue(eqv(subtract(0, makeBignum("129834789213412345678910")), makeBignum("-129834789213412345678910"))); assertTrue(eqv(subtract(0, makeFloat(0.12345)), makeFloat(-0.12345))); assertTrue(eqv(subtract(0, makeFloat(0)), negative_zero)); assertTrue(eqv(subtract(0, negative_zero), makeFloat(0))); assertTrue(eqv(subtract(0, nan), nan)); assertTrue(eqv(subtract(0, inf), negative_inf)); assertTrue(eqv(subtract(0, negative_inf), inf)); } }); describe('multiply', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'negative zero': function() { assertTrue(eqv(makeFloat(0), multiply(negative_zero, negative_zero))); assertTrue(eqv(makeFloat(0), multiply(makeFloat(0), negative_zero))); assertTrue(eqv(negative_zero, multiply(negative_zero, makeFloat(0)))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(0, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(-1, makeComplex(makeFloat(0), makeFloat(0))))); assertTrue(eqv(makeComplex(negative_zero, negative_zero), multiply(makeComplex(makeFloat(0), makeFloat(0)), -1))); }, '1 acts as the identity': function() { assertTrue(eqv(0, multiply(1, 0))); assertTrue(eqv(1, multiply(1, 1))); assertTrue(eqv(-1, multiply(1, -1))); assertTrue(eqv(1234, multiply(1, 1234))); assertTrue(eqv(makeBignum("1929365432165895132685321689"), multiply(1, makeBignum("1929365432165895132685321689")))); assertTrue(eqv(makeBignum("-1929365432165895132685321689"), multiply(1, makeBignum("-1929365432165895132685321689")))); assertTrue(eqv(makeRational(1, 24), multiply(1, makeRational(1, 24)))); assertTrue(eqv(makeRational(-21, 24), multiply(1, makeRational(-21, 24)))); assertTrue(eqv(makeFloat(123.45), multiply(1, makeFloat(123.45)))); assertTrue(eqv(makeFloat(0), multiply(1, makeFloat(0)))); assertTrue(eqv(nan, multiply(1, nan))); assertTrue(eqv(inf, multiply(1, inf))); assertTrue(eqv(negative_inf, multiply(1, negative_inf))); assertTrue(eqv(negative_zero, multiply(1, negative_zero))); } }); describe('divide', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this }, 'division by zeros' : function() { assertFails(function() {divide(1, 0);}); assertFails(function() {divide(makeRational(1, 2), 0);}); assertFails(function() {divide(makeComplex(1, 2), 0);}); assertTrue(eqv(inf, divide(1, makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(1, negative_zero))); assertTrue(eqv(inf, divide(makeFloat(42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(-42), makeFloat(0.0)))); assertTrue(eqv(negative_inf, divide(makeFloat(42), negative_zero))); assertTrue(eqv(inf, divide(makeFloat(-42), negative_zero))); assertTrue(eqv(inf, divide(makeRational(1, 2), makeFloat(0.0)))); assertTrue(eqv(makeComplex(inf, inf), divide(makeComplex(1, 2), makeFloat(0.0)))); }, 'division 0 by 0': function() { assertFails(function() { divide(0, 0); }); assertFails(function() { divide(makeFloat(0), 0); }); assertTrue(eqv(negative_zero, divide(makeFloat(0), makeFloat(0)))); assertTrue(eqv(0, divide(0, makeFloat(0)))); } }); describe('greaterThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThanOrEqual', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('greaterThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lessThan', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('expt', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum overflows to bignum': function() { // FIXME }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this + }, + 'expt of anything to zero is 1' : function() { + assertTrue(eqv(1, expt(nan, 0))); + assertTrue(eqv(1, expt(inf, 0))); + assertTrue(eqv(1, expt(negative_inf, 0))); + assertTrue(eqv(1, expt(negative_zero, 0))); + assertTrue(eqv(1, expt(0, 0))); } }); describe('modulo', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('numerator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('denominator', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('abs', { 'fixnums': function() { assertEquals(0, abs(0)); assertEquals(42, abs(42)); assertEquals(42, abs(-42)); assertEquals(1, abs(-1)); }, 'bignums': function() { assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("23569236859962835638935268952936825689536829253968")))); assertTrue(eqv(makeBignum("23569236859962835638935268952936825689536829253968"), abs(makeBignum("-23569236859962835638935268952936825689536829253968")))); assertEquals(makeBignum("1"), abs(makeBignum("-1"))); assertEquals(makeBignum("1"), abs(makeBignum("1"))); assertEquals(makeBignum("0"), abs(makeBignum("0"))); }, 'rationals': function() { assertEquals(makeRational(2, 1), abs(makeRational(-2, 1))); assertEquals(makeRational(2, 1), abs(makeRational(2, 1))); assertEquals(makeRational(0, 1), abs(makeRational(0, 1))); assertEquals(makeRational(3298, 28), abs(makeRational(3298, 28))); assertEquals(makeRational(3298, 28), abs(makeRational(-3298, 28))); }, 'floats': function() { assertEquals(makeFloat(0.0), abs(makeFloat(0.0))); assertTrue(eqv(makeFloat(0.0), abs(negative_zero))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(1342.7)))); assertTrue(eqv(makeFloat(1342.7), abs(makeFloat(-1342.7)))); }, 'complex': function() { assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(-2, 0)))); assertTrue(eqv(makeComplex(2, 0), abs(makeComplex(2, 0)))); } }); describe('floor', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('ceiling', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('conjugate', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('magnitude', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('log', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('angle', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('atan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('cos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(exp(0), 1)); assertTrue(equals(exp(1), e)); assertTrue(approxEquals(exp(makeRational(2)), sqr(e), makeFloat(0.0001))); }, testExpt : function(){ var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( expt(i, i), exp(multiply(pi, makeRational(-1, 2))))); assertTrue(equals( expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals(expt(makeComplex(makeRational(3,4), makeRational(7,8)), makeRational(2)), makeComplex(makeRational(-13, 64), makeRational(21, 16)))); }, testSin : function(){ - assertTrue(equals(Kernel.sin(divide(PI, makeFloat(2))), 1)); + assertTrue(equals(sin(divide(pi, makeFloat(2))), 1)); }, testCos : function(){ - assertTrue(equals(Kernel.cos(0), 1)); + assertTrue(equals(cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); - assertEquals(1764, sqr(n1).toFixnum()); + assertEquals(1764, toFixnum(sqr(n1))); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); - assertEquals(n2, Kernel.integer_dash_sqrt(n1)); - assertFails(function() { Kernel.integer_dash_sqrt(makeFloat(3.5)); }); + assertEquals(n2, integerSqrt(n1)); + assertFails(function() { integerSqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ - assertTrue(equals(Kernel.acos(1), 0)); - assertTrue(equals(Kernel.acos(makeFloat(-1)), PI)); + assertTrue(equals(acos(1), 0)); + assertTrue(equals(acos(makeFloat(-1)), pi)); }, testAsin : function(){ - assertTrue(equals( - Kernel.asin(0), 0)); - assertTrue(equals(Kernel.asin(-1), PI.half().minus())); - assertTrue(equals( - Kernel.asin(1), PI.half())); - - assertTrue(equals( - Kernel.asin(makeRational(1, 4)), - makeFloat(0.25268025514207865))); - - assertTrue(equals( - Kernel.asin(makeComplex(1, 5)), - makeComplex(0.1937931365549321, - 2.3309746530493123))); + assertTrue(equals(asin(0), + 0)); + assertTrue(equals(asin(-1), + multiply(pi, makeRational(-1, 2)))); + assertTrue(equals(asin(1), + divide(pi, 2))); + assertTrue(equals(asin(makeRational(1, 4)), + makeFloat(0.25268025514207865))); + assertTrue(equals(asin(makeComplex(1, 5)), + makeComplex(makeFloat(0.1937931365549321), + makeFloat(2.3309746530493123)))); }, testTan : function(){ - assertTrue(equals(Kernel.tan(0), 0)); + assertTrue(equals(tan(0), 0)); }, testComplex_question_ : function(){ - assertTrue(Kernel.complex_question_(PI)); - assertTrue(Kernel.complex_question_(1)); - assertTrue(Kernel.complex_question_(makeFloat(2.718))); - assertTrue(Kernel.complex_question_(makeComplex(0,1))); - assertTrue(!Kernel.complex_question_(plt.types.Empty.EMPTY)); - assertTrue(!Kernel.complex_question_(String.makeInstance("hi"))); - assertTrue(!Kernel.complex_question_(Symbol.makeInstance('h'))); + assertTrue(isSchemeNumber(pi)); + assertTrue(isSchemeNumber(1)); + assertTrue(isSchemeNumber(makeFloat(2.718))); + assertTrue(isSchemeNumber(makeComplex(0,1))); }, testMakePolar : function() { assertTrue(equals(Kernel.make_dash_polar(makeRational(5), makeRational(0)), makeComplex(makeRational(5),makeRational( 0)))); var n = Kernel.make_dash_polar(makeRational(5), - PI); + pi); var delta = makeFloat(0.0000001); assertTrue(approxEquals(Kernel.imag_dash_part(n), makeRational(0), delta)); assertTrue(approxEquals(Kernel.real_dash_part(n), makeRational(-5), delta)); }, testMakeRectangular: function() { assertTrue(equals(Kernel.make_dash_rectangular (makeRational(4), makeRational(3)), makeComplex(makeRational(4),makeRational( 3)))); assertTrue(equals(Kernel.make_dash_rectangular (makeRational(5), makeRational(4)), makeComplex(makeRational(5),makeRational( 4)))); }, testCosh : function(){ assertTrue(equals(Kernel.cosh(0), 1)); }, testSinh : function(){ - assertTrue(equals(Kernel.sinh(0), 0)); + assertTrue(equals(sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(Kernel.denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(Kernel.denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(Kernel.numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(Kernel.numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(Kernel.exact_question_(makeRational(3))); assertTrue(! Kernel.exact_question_(makeFloat(3.0))); assertTrue(! Kernel.exact_question_(makeFloat(3.5))); }, testIsInexact : function() { assertTrue(! Kernel.inexact_question_(makeRational(3))); assertTrue(Kernel.inexact_question_(makeFloat(3.0))); assertTrue(Kernel.inexact_question_(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0) )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3) )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); - assertTrue(equals(Kernel.ceiling(PI), makeFloat(4))); + assertTrue(equals(Kernel.ceiling(pi), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); - assertTrue(equals(Kernel.floor(PI), makeFloat(3))); + assertTrue(equals(Kernel.floor(pi), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); - assertTrue(equals(Kernel.imag_dash_part(PI), 0)); + assertTrue(equals(Kernel.imag_dash_part(pi), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); - assertTrue(equals(Kernel.real_dash_part(PI), PI)); + assertTrue(equals(Kernel.real_dash_part(pi), pi)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(plt.types.makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ - assertTrue(Kernel.real_question_(PI)); + assertTrue(Kernel.real_question_(pi)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.real_question_(String.makeInstance("hi"))); assertTrue(!Kernel.real_question_(Symbol.makeInstance('h'))); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), Rational.NEGATIVE_ONE)); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
d8d7334dab4fcacc69840da993a7884013ebcefd
Implementing expt
diff --git a/src/js-numbers.js b/src/js-numbers.js index 4d1a86e..c216b16 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -205,2372 +205,2408 @@ if (! this['plt']['lib']['Numbers']) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { return Math.floor(Math.sqrt(x)); } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; + // fastExpt: computes n^k by squaring. + // n^k = (n^2)^(k/2) + // Assumes k is non-negative integer. + var fastExpt = function(n, k) { + var acc = 1; + while (true) { + if (_integerIsZero(k)) { + return acc; + } + if (equals(modulo(k, 2), 0)) { + n = multiply(n, n); + k = divide(k, 2); + } else { + acc = multiply(acc, n); + k = subtract(k, 1); + } + } + }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { + if (m instanceof Complex) { + m = realPart(m); + } + if (n instanceof Complex) { + n = realPart(n); + } + if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { + if (m instanceof Complex) { + m = realPart(m); + } + if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. // log: -> scheme-number // Produce the log. // angle: -> scheme-number // Produce the angle. // atan: -> scheme-number // Produce the arc tangent. // cos: -> scheme-number // Produce the cosine. // sin: -> scheme-number // Produce the sine. // expt: scheme-number -> scheme-number // Produce the power to the input. // exp: -> scheme-number // Produce e raised to the given power. // acos: -> scheme-number // Produce the arc cosine. // asin: -> scheme-number // Produce the arc sine. // imaginaryPart: -> scheme-number // Produce the imaginary part // realPart: -> scheme-number // Produce the real part. // round: -> scheme-number // Round to the nearest integer. // equals: scheme-number -> boolean // Produce true if the given number of the same type is equal. ////////////////////////////////////////////////////////////////////// // Rationals var Rational = function(n, d) { this.n = n; this.d = d; }; Rational.prototype.toString = function() { if (_integerIsOne(this.d)) { return this.n.toString() + ""; } else { return this.n.toString() + "/" + this.d.toString(); } }; Rational.prototype.level = 1; Rational.prototype.liftTo = function(target) { if (target.level === 2) return new FloatPoint( _integerDivideToFixnum(this.n, this.d)); if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; Rational.prototype.isFinite = function() { return true; }; Rational.prototype.equals = function(other) { return (other instanceof Rational && _integerEquals(this.n, other.n) && _integerEquals(this.d, other.d)); }; Rational.prototype.isInteger = function() { return _integerIsOne(this.d); }; Rational.prototype.isRational = function() { return true; }; Rational.prototype.isReal = function() { return true; }; Rational.prototype.add = function(other) { return Rational.makeInstance(_integerAdd(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.subtract = function(other) { return Rational.makeInstance(_integerSubtract(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)), _integerMultiply(this.d, other.d)); }; Rational.prototype.negate = function() { return Rational.makeInstance(-this.n, d) }; Rational.prototype.multiply = function(other) { return Rational.makeInstance(_integerMultiply(this.n, other.n), _integerMultiply(this.d, other.d)); }; Rational.prototype.divide = function(other) { if (_integerIsZero(this.d) || _integerIsZero(other.n)) { throwRuntimeError("division by zero", this, other); } return Rational.makeInstance(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.toExact = function() { return this; }; Rational.prototype.isExact = function() { return true; }; Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { return fromFixnum(Math.floor(this.n / this.d)); }; Rational.prototype.ceiling = function() { return fromFixnum(Math.ceil(this.n / this.d)); }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ + if (isExactInteger(a) && greaterThanOrEqual(a, 0)) { + return fastExpt(this, a); + } return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // _rationalCache = {}; // (function() { // var i; // for(i = -500; i < 500; i++) { // _rationalCache[i] = new Rational(i, 1); // } // })(); // Rational.NEGATIVE_ONE = new Rational(-1, 1); // Rational.ZERO = new Rational(0, 1); // Rational.ONE = new Rational(1, 1); // Rational.TWO = new Rational(2, 1); // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, Rational.TWO); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; - Complex.prototype.expt= function(y){ + + Complex.prototype.expt = function(y){ + if (isExactInteger(y) && greaterThanOrEqual(y, 0)) { + return fastExpt(this, y); + } var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract( 1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply( Rational.TWO, atan(divide( this, add( 1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return makeRational(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return makeComplex(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = []; var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = [], i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r.push(int2char(d)); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r.push(int2char(d)); } } return m?r.join(""):"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { diff --git a/test/tests.js b/test/tests.js index f92c42d..a625b00 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2306,938 +2306,931 @@ describe('realPart', { describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, conjugate(n1))); assertTrue(equals(n2, conjugate(n2))); assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); assertTrue(equals(n1, magnitude(n1))); assertTrue(equals(n2, magnitude(n2))); assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ assertTrue(greaterThan(makeRational(2,1), makeRational(1,1))); assertTrue(greaterThan(makeFloat(2.1), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeFloat(2.0), makeRational(2,1))); assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), makeRational(2,1))); assertTrue(lessThan(makeRational(2), makeRational(3))); assertTrue(! lessThan(makeRational(3), makeRational(2))); }, testComparisonMore: function() { assertTrue(! greaterThan(makeRational(2), makeRational(3))); assertTrue(greaterThan(makeRational(3), makeRational(2))); assertTrue(! greaterThan(makeRational(3), makeRational(3))); assertTrue(lessThanOrEqual(makeRational(17), makeRational(17))); assertTrue(lessThanOrEqual(makeRational(16), makeRational(17))); assertTrue(!lessThanOrEqual(makeRational(16), makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); assertTrue(lessThan(makeRational(5, 1), upper)); assertTrue(lessThan(makeRational(6, 1), upper)); assertTrue(lessThan(makeRational(7, 1), upper)); assertTrue(lessThan(makeRational(8, 1), upper)); assertTrue(lessThan(makeRational(9, 1), upper)); for (var i = 0; i < 60; i++) { assertTrue(lessThan (num, upper)); num = add(num, 1); } }, testAtan : function(){ assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ assertTrue(equals(log(1), 0)); assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); assertTrue(equals(angle(makeFloat(-1)), pi)); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), multiply(pi, makeFloat(0.75)))); assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), multiply(pi, makeFloat(-0.75)))); assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ - assertTrue(equals(Kernel.exp(0), 1, [])); - assertTrue(equals(Kernel.exp(1), - Kernel.e, [])); - assertTrue(equals_tilde_(Kernel.exp(makeRational(2)), - Kernel.sqr(Kernel.e), + assertTrue(equals(exp(0), 1)); + assertTrue(equals(exp(1), + e)); + assertTrue(approxEquals(exp(makeRational(2)), + sqr(e), makeFloat(0.0001))); }, testExpt : function(){ - var i = plt.types.makeComplex( + var i = makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( - Kernel.expt(i, i), - Kernel.exp(PI.half().minus()))); + expt(i, i), + exp(multiply(pi, makeRational(-1, 2))))); - assertTrue(equals( - Kernel.expt(makeFloat(2), - makeFloat(3)), - makeFloat(8))); + assertTrue(equals( + expt(makeFloat(2), + makeFloat(3)), + makeFloat(8))); - assertTrue(equals( - Kernel.expt(makeComplex( - makeRational(3,4), - makeRational(7,8)), - makeRational(2))), - makeComplex(makeRational(-13, 64), - makeRational(21, 16))); + assertTrue(equals(expt(makeComplex(makeRational(3,4), + makeRational(7,8)), + makeRational(2)), + makeComplex(makeRational(-13, 64), + makeRational(21, 16)))); }, testSin : function(){ assertTrue(equals(Kernel.sin(divide(PI, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(Kernel.cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); - assertEquals(1764, Kernel.sqr(n1).toFixnum()); - assertFails(isTypeMismatch, - function() { Kernel.sqr("42"); }); + assertEquals(1764, sqr(n1).toFixnum()); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, Kernel.integer_dash_sqrt(n1)); assertFails(function() { Kernel.integer_dash_sqrt(makeFloat(3.5)); }); }, testSqrt : function(){ - assertTrue(equals(Kernel.sqrt(makeFloat(4)), makeFloat(2))); - assertTrue(equals(Kernel.sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); + assertTrue(equals(sqrt(makeFloat(4)), makeFloat(2))); + assertTrue(equals(sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(Kernel.acos(1), 0)); assertTrue(equals(Kernel.acos(makeFloat(-1)), PI)); }, testAsin : function(){ assertTrue(equals( Kernel.asin(0), 0)); assertTrue(equals(Kernel.asin(-1), PI.half().minus())); assertTrue(equals( Kernel.asin(1), PI.half())); assertTrue(equals( Kernel.asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals( Kernel.asin(makeComplex(1, 5)), makeComplex(0.1937931365549321, 2.3309746530493123))); }, testTan : function(){ assertTrue(equals(Kernel.tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(Kernel.complex_question_(PI)); assertTrue(Kernel.complex_question_(1)); assertTrue(Kernel.complex_question_(makeFloat(2.718))); assertTrue(Kernel.complex_question_(makeComplex(0,1))); assertTrue(!Kernel.complex_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.complex_question_(String.makeInstance("hi"))); assertTrue(!Kernel.complex_question_(Symbol.makeInstance('h'))); }, testMakePolar : function() { assertTrue(equals(Kernel.make_dash_polar(makeRational(5), makeRational(0)), makeComplex(makeRational(5),makeRational( 0)))); var n = Kernel.make_dash_polar(makeRational(5), PI); var delta = makeFloat(0.0000001); - assertTrue(equals_tilde_(Kernel.imag_dash_part(n), + assertTrue(approxEquals(Kernel.imag_dash_part(n), makeRational(0), delta)); - assertTrue(equals_tilde_(Kernel.real_dash_part(n), + assertTrue(approxEquals(Kernel.real_dash_part(n), makeRational(-5), delta)); }, testMakeRectangular: function() { assertTrue(equals(Kernel.make_dash_rectangular (makeRational(4), makeRational(3)), makeComplex(makeRational(4),makeRational( 3)))); assertTrue(equals(Kernel.make_dash_rectangular (makeRational(5), makeRational(4)), makeComplex(makeRational(5),makeRational( 4)))); }, testCosh : function(){ assertTrue(equals(Kernel.cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(Kernel.sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(Kernel.denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(Kernel.denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(Kernel.numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(Kernel.numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(Kernel.exact_question_(makeRational(3))); assertTrue(! Kernel.exact_question_(makeFloat(3.0))); assertTrue(! Kernel.exact_question_(makeFloat(3.5))); }, testIsInexact : function() { assertTrue(! Kernel.inexact_question_(makeRational(3))); assertTrue(Kernel.inexact_question_(makeFloat(3.0))); assertTrue(Kernel.inexact_question_(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), - makeFloat(3.0), - [])); + makeFloat(3.0) + )); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), - makeRational(3), - [])); + makeRational(3) + )); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { - assertTrue(equals(0, - multiply([0, - inf]), - [])); + assertTrue(equals(0, multiply(0, inf))); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(PI), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(PI), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(PI), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(PI), PI)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(plt.types.makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(PI)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.real_question_(String.makeInstance("hi"))); assertTrue(!Kernel.real_question_(Symbol.makeInstance('h'))); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), Rational.NEGATIVE_ONE)); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
dyoo/js-numbers
fde4fc6ac5dddff612adfff3e1cbe933dbdef7dd
up to angle.
diff --git a/src/js-numbers.js b/src/js-numbers.js index 430f631..4d1a86e 100644 --- a/src/js-numbers.js +++ b/src/js-numbers.js @@ -1,1024 +1,1025 @@ // Scheme numbers. if (! this['plt']) { this['plt'] = {}; } if (! this['plt']['lib']) { this['plt']['lib'] = {}; } if (! this['plt']['lib']['Numbers']) { this['plt']['lib']['Numbers'] = {}; } // The numeric tower has the following levels: // integers // rationals // floats // complex numbers // // with the representations: // integers: fixnum or BigInteger [level=0] // rationals: Rational [level=1] // floats: FloatPoint [level=2] // complex numbers: Complex [level=3] // We try to stick with the unboxed fixnum representation for // integers, since that's what scheme programs commonly deal with, and // we want that common type to be lightweight. // A boxed-scheme-number is either BigInteger, Rational, FloatPoint, or Complex. // An integer-scheme-number is either fixnum or BigInteger. (function() { // Abbreviation var Numbers = plt.lib.Numbers; // makeNumericBinop: (fixnum fixnum -> any) (scheme-number scheme-number -> any) -> (scheme-number scheme-number) X // Creates a binary function that works either on fixnums or boxnums. // Applies the appropriate binary function, ensuring that both scheme numbers are // lifted to the same level. var makeNumericBinop = function(onFixnums, onBoxednums, options) { options = options || {}; return function(x, y) { if (options.isXSpecialCase && options.isXSpecialCase(x)) return options.onXSpecialCase(x, y); if (options.isYSpecialCase && options.isYSpecialCase(y)) return options.onYSpecialCase(x, y); if (typeof(x) === 'number' && typeof(y) === 'number') { return onFixnums(x, y); } if (typeof(x) === 'number') { x = liftFixnumInteger(x, y); } if (typeof(y) === 'number') { y = liftFixnumInteger(y, x); } if (x.level < y.level) x = x.liftTo(y); if (y.level < x.level) y = y.liftTo(x); return onBoxednums(x, y); }; } // fromFixnum: fixnum -> scheme-number var fromFixnum = function(x) { if (isNaN(x) || (! isFinite(x))) { return FloatPoint.makeInstance(x); } var nf = Math.floor(x); if (nf === x) { if (isOverflow(nf)) { return makeBignum(x); } else { return nf; } } else { return FloatPoint.makeInstance(x); } }; // liftFixnumInteger: fixnum-integer boxed-scheme-number -> boxed-scheme-number // Lifts up fixnum integers to a boxed type. var liftFixnumInteger = function(x, other) { switch(other.level) { case 0: // BigInteger return makeBignum(x); case 1: // Rational return new Rational(x, 1); case 2: // FloatPoint return new FloatPoint(x); case 3: // Complex return new Complex(x, 0); default: return throwRuntimeError("IMPOSSIBLE: cannot lift fixnum integer to " + other.toString(), x, other); } }; // throwRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // Throws a runtime error with the given message string. var throwRuntimeError = function(msg, x, y) { Numbers['onThrowRuntimeError'](msg, x, y); }; // onThrowRuntimeError: string (scheme-number | undefined) (scheme-number | undefined) -> void // By default, will throw a new Error with the given message. // Override Numbers['onThrowRuntimeError'] if you need to do something special. var onThrowRuntimeError = function(msg, x, y) { throw new Error(msg); }; // isSchemeNumber: any -> boolean // Returns true if the thing is a scheme number. var isSchemeNumber = function(thing) { return (typeof(thing) === 'number' || (thing instanceof Rational || thing instanceof FloatPoint || thing instanceof Complex || thing instanceof BigInteger)); }; // isRational: scheme-number -> boolean var isRational = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isRational())); }; // isReal: scheme-number -> boolean var isReal = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isReal())); }; // isExact: scheme-number -> boolean var isExact = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isExact())); }; // isInteger: scheme-number -> boolean var isInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger())); }; // isExactInteger: scheme-number -> boolean var isExactInteger = function(n) { return (typeof(n) === 'number' || (isSchemeNumber(n) && n.isInteger() && n.isExact())); } // toFixnum: scheme-number -> javascript-number var toFixnum = function(n) { if (typeof(n) === 'number') return n; return n.toFixnum(); }; // toExact: scheme-number -> scheme-number var toExact = function(n) { if (typeof(n) === 'number') return n; return n.toExact(); }; ////////////////////////////////////////////////////////////////////// // add: scheme-number scheme-number -> scheme-number var add = makeNumericBinop( function(x, y) { var sum = x + y; if (isOverflow(sum)) { return (makeBignum(x)).add(makeBignum(y)); } else { return sum; } }, function(x, y) { return x.add(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return y; }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // subtract: scheme-number scheme-number -> scheme-number var subtract = makeNumericBinop( function(x, y) { var diff = x - y; if (isOverflow(diff)) { return (makeBignum(x)).subtract(makeBignum(y)); } else { return diff; } }, function(x, y) { return x.subtract(y); }, {isXSpecialCase: function(x) { return isExactInteger(x) && _integerIsZero(x) }, onXSpecialCase: function(x, y) { return negate(y); }, isYSpecialCase: function(y) { return isExactInteger(y) && _integerIsZero(y) }, onYSpecialCase: function(x, y) { return x; } }); // mulitply: scheme-number scheme-number -> scheme-number var multiply = makeNumericBinop( function(x, y) { var prod = x * y; if (isOverflow(prod)) { return (makeBignum(x)).multiply(makeBignum(y)); } else { return prod; } }, function(x, y) { return x.multiply(y); }, {isXSpecialCase: function(x) { return (isExactInteger(x) && (_integerIsZero(x) || _integerIsOne(x) || _integerIsNegativeOne(x))) }, onXSpecialCase: function(x, y) { if (_integerIsZero(x)) return 0; if (_integerIsOne(x)) return y; if (_integerIsNegativeOne(x)) return negate(y); }, isYSpecialCase: function(y) { return (isExactInteger(y) && (_integerIsZero(y) || _integerIsOne(y) || _integerIsNegativeOne(y)))}, onYSpecialCase: function(x, y) { if (_integerIsZero(y)) return 0; if (_integerIsOne(y)) return x; if (_integerIsNegativeOne(y)) return negate(x); } }); // divide: scheme-number scheme-number -> scheme-number var divide = makeNumericBinop( function(x, y) { if (_integerIsZero(y)) throwRuntimeError("division by zero", x, y); var div = x / y; if (isOverflow(div)) { return (makeBignum(x)).divide(makeBignum(y)); } else if (Math.floor(div) !== div) { return Rational.makeInstance(x, y); } else { return div; } }, function(x, y) { return x.divide(y); }); // equals: scheme-number scheme-number -> boolean var equals = makeNumericBinop( function(x, y) { return x === y; }, function(x, y) { return x.equals(y); }); // eqv: scheme-number scheme-number -> boolean var eqv = function(x, y) { if (x === y) return true; if (typeof(x) === 'number' && typeof(y) === 'number') return x === y; if (x === NEGATIVE_ZERO || y === NEGATIVE_ZERO) return x === y; if (x instanceof Complex || y instanceof Complex) { return (eqv(realPart(x), realPart(y)) && eqv(imaginaryPart(x), imaginaryPart(y))); } var ex = isExact(x), ey = isExact(y); return (((ex && ey) || (!ex && !ey)) && equals(x, y)); }; // approxEqual: scheme-number scheme-number scheme-number -> boolean var approxEquals = function(x, y, delta) { return lessThan(abs(subtract(x, y)), delta); }; // greaterThanOrEqual: scheme-number scheme-number -> boolean var greaterThanOrEqual = makeNumericBinop( function(x, y) { return x >= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError( "greaterThanOrEqual: couldn't be applied to complex number", x, y); return x.greaterThanOrEqual(y); }); // lessThanOrEqual: scheme-number scheme-number -> boolean var lessThanOrEqual = makeNumericBinop( function(x, y){ return x <= y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThanOrEqual: couldn't be applied to complex number", x, y); return x.lessThanOrEqual(y); }); // greaterThan: scheme-number scheme-number -> boolean var greaterThan = makeNumericBinop( function(x, y){ return x > y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("greaterThan: couldn't be applied to complex number", x, y); return x.greaterThan(y); }); // lessThan: scheme-number scheme-number -> boolean var lessThan = makeNumericBinop( function(x, y){ return x < y; }, function(x, y) { if (!(isReal(x) && isReal(y))) throwRuntimeError("lessThan: couldn't be applied to complex number", x, y); return x.lessThan(y); }); // expt: scheme-number scheme-number -> scheme-number var expt = makeNumericBinop( function(x, y){ if (y >= 0) { var pow = Math.pow(x, y); if (isOverflow(pow)) { return (makeBignum(x)).expt(makeBignum(y)); } else { return pow; } } else { return (makeBignum(x)).expt(makeBignum(y)); } }, function(x, y) { return x.expt(y); }); // exp: scheme-number -> scheme-number var exp = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.exp(n)); } return n.exp(); }; // modulo: scheme-number scheme-number -> scheme-number var modulo = function(m, n) { if (! isInteger(m)) { throwRuntimeError('modulo: the first argument ' + m + " is not an integer.", m, n); } if (! isInteger(n)) { throwRuntimeError('modulo: the second argument ' + n + " is not an integer.", m, n); } var result; if (typeof(m) === 'number') { result = m % n; if (n < 0) { if (result <= 0) return result; else return result + n; } else { if (result < 0) return result + n; else return result; } } result = _integerModulo(floor(m), floor(n)); // The sign of the result should match the sign of n. if (lessThan(n, 0)) { if (lessThanOrEqual(result, 0)) { return result; } return add(result, n); } else { if (lessThan(result, 0)) { return add(result, n); } return result; } }; // numerator: scheme-number -> scheme-number var numerator = function(n) { if (typeof(n) === 'number') return n; return n.numerator(); }; // denominator: scheme-number -> scheme-number var denominator = function(n) { if (typeof(n) === 'number') return 1; return n.denominator(); }; // sqrt: scheme-number -> scheme-number var sqrt = function(n) { if (typeof(n) === 'number') { if (n >= 0) { var result = Math.sqrt(n); if (Math.floor(result) === result) { return result; } else { return FloatPoint.makeInstance(result); } } else { return (makeBignum(n)).sqrt(); } } return n.sqrt(); }; // abs: scheme-number -> scheme-number var abs = function(n) { if (typeof(n) === 'number') { return Math.abs(n); } return n.abs(); }; // floor: scheme-number -> scheme-number var floor = function(n) { if (typeof(n) === 'number') return n; return n.floor(); }; // ceiling: scheme-number -> scheme-number var ceiling = function(n) { if (typeof(n) === 'number') return n; return n.ceiling(); }; // conjugate: scheme-number -> scheme-number var conjugate = function(n) { if (typeof(n) === 'number') return n; return n.conjugate(); }; // magnitude: scheme-number -> scheme-number var magnitude = function(n) { if (typeof(n) === 'number') return Math.abs(n); return n.magnitude(); }; + // log: scheme-number -> scheme-number var log = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.log(n)); } return n.log(); }; // angle: scheme-number -> scheme-number var angle = function(n) { if (typeof(n) === 'number') { if (n > 0) return 0; else return FloatPoint.pi; } return n.angle(); }; // tan: scheme-number -> scheme-number var tan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.tan(n)); } return n.tan(); }; // atan: scheme-number -> scheme-number var atan = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.atan(n)); } return n.atan(); }; // cos: scheme-number -> scheme-number var cos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.cos(n)); } return n.cos(); }; // sin: scheme-number -> scheme-number var sin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.sin(n)); } return n.sin(); }; // acos: scheme-number -> scheme-number var acos = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.acos(n)); } return n.acos(); }; // asin: scheme-number -> scheme-number var asin = function(n) { if (typeof(n) === 'number') { return FloatPoint.makeInstance(Math.asin(n)); } return n.asin(); }; // imaginaryPart: scheme-number -> scheme-number var imaginaryPart = function(n) { if (typeof(n) === 'number') { return 0; } return n.imaginaryPart(); }; // realPart: scheme-number -> scheme-number var realPart = function(n) { if (typeof(n) === 'number') { return n; } return n.realPart(); }; // round: scheme-number -> scheme-number var round = function(n) { if (typeof(n) === 'number') { return n; } return n.round(); }; // sqr: scheme-number -> scheme-number var sqr = function(x) { return multiply(x, x); }; // integerSqrt: scheme-number -> scheme-number var integerSqrt = function(x) { if (typeof (x) === 'number') { return Math.floor(Math.sqrt(x)); } return x.integerSqrt(); }; // gcd: scheme-number [scheme-number ...] -> scheme-number var gcd = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('gcd: the argument ' + first.toString() + " is not an integer.", first); } var a = abs(first), t, b; for(var i = 0; i < rest.length; i++) { b = abs(rest[i]); if (! isInteger(b)) { throwRuntimeError('gcd: the argument ' + b.toString() + " is not an integer.", b); } while (! _integerIsZero(b)) { t = a; a = b; b = integerModulo(t, b); } } return a; }; // lcm: scheme-number [scheme-number ...] -> scheme-number var lcm = function(first, rest) { if (! isInteger(first)) { throwRuntimeError('lcm: the argument ' + first.toString() + " is not an integer.", first); } var result = abs(first); if (_integerIsZero(result)) { return 0; } for (var i = 0; i < rest.length; i++) { if (! isInteger(rest[i])) { throwRuntimeError('lcm: the argument ' + rest[i].toString() + " is not an integer.", rest[i]); } var divisor = gcd(result, rest[i]); if (_integerIsZero(divisor)) { return 0; } result = divide(multiply(result, rest[i]), divisor); } return result; }; ////////////////////////////////////////////////////////////////////// // Helpers // IsFinite: scheme-number -> boolean // Returns true if the scheme number is finite or not. var isSchemeNumberFinite = function(n) { if (typeof(n) === 'number') { return isFinite(n); } else { return n.isFinite(); } }; // isOverflow: javascript-number -> boolean // Returns true if we consider the number an overflow. var MIN_FIXNUM = -(9e15); var MAX_FIXNUM = (9e15); var isOverflow = function(n) { return (n < MIN_FIXNUM || MAX_FIXNUM < n); }; // negate: scheme-number -> scheme-number // multiplies a number times -1. var negate = function(n) { if (typeof(n) === 'number') { return -n; } return n.negate(); }; // halve: scheme-number -> scheme-number // Divide a number by 2. var halve = function(n) { return divide(n, 2); }; // timesI: scheme-number scheme-number // multiplies a number times i. var timesI = function(x) { return multiply(x, plusI); }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Integer operations // Integers are either represented as fixnums or as BigIntegers. // makeIntegerBinop: (fixnum fixnum -> X) (BigInteger BigInteger -> X) -> X // Helper to collect the common logic for coersing integer fixnums or bignums to a // common type before doing an operation. var makeIntegerBinop = function(onFixnums, onBignums, options) { options = options || {}; return (function(m, n) { if (typeof(m) === 'number' && typeof(n) === 'number') { var result = onFixnums(m, n); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint || n instanceof FloatPoint) { if (options.doNotCoerseToFloating) { return onFixnums(toFixnum(m), toFixnum(n)); } else { return FloatPoint.makeInstance( onFixnums(toFixnum(m), toFixnum(n))); } } if (typeof(m) === 'number') { m = makeBignum(m); } if (typeof(n) === 'number') { n = makeBignum(n); } return onBignums(m, n); }); }; var makeIntegerUnOp = function(onFixnums, onBignums, options) { options = options || {}; return (function(m) { if (typeof(m) === 'number') { var result = onFixnums(m); if (! isOverflow(result) || (options.ignoreOverflow)) { return result; } } if (m instanceof FloatPoint) { return onFixnums(toFixnum(m)); } if (typeof(m) === 'number') { m = makeBignum(m); } return onBignums(m); }); }; // _integerModulo: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerModulo = makeIntegerBinop( function(m, n) { return m % n; }, function(m, n) { return bnMod.call(m, n); }); // _integerGcd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerGcd = makeIntegerBinop( function(a, b) { var t; while (b !== 0) { t = a; a = b; b = t % b; } return a; }, function(m, n) { return bnGCD.call(m, n); }); // _integerIsZero: integer-scheme-number -> boolean // Returns true if the number is zero. var _integerIsZero = makeIntegerUnOp( function(n){ return n === 0; }, function(n) { return bnEquals.call(n, BigInteger.ZERO); } ); // _integerIsOne: integer-scheme-number -> boolean var _integerIsOne = makeIntegerUnOp( function(n) { return n === 1; }, function(n) { return bnEquals.call(n, BigInteger.ONE); }); // _integerIsNegativeOne: integer-scheme-number -> boolean var _integerIsNegativeOne = makeIntegerUnOp( function(n) { return n === -1; }, function(n) { return bnEquals.call(n, BigInteger.NEGATIVE_ONE); }); // _integerAdd: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerAdd = makeIntegerBinop( function(m, n) { return m + n; }, function(m, n) { return bnAdd.call(m, n); }); // _integerSubtract: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerSubtract = makeIntegerBinop( function(m, n) { return m - n; }, function(m, n) { return bnSubtract.call(m, n); }); // _integerMultiply: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerMultiply = makeIntegerBinop( function(m, n) { return m * n; }, function(m, n) { return bnMultiply.call(m, n); }); //_integerQuotient: integer-scheme-number integer-scheme-number -> integer-scheme-number var _integerQuotient = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return bnDivide.call(m, n); }); // _integerDivideToFixnum: integer-scheme-number integer-scheme-number -> fixnum var _integerDivideToFixnum = makeIntegerBinop( function(m, n) { return m / n; }, function(m, n) { return toFixnum(m) / toFixnum(n); }, {ignoreOverflow: true, doNotCoerseToFloating: true}); // _integerEquals: integer-scheme-number integer-scheme-number -> boolean var _integerEquals = makeIntegerBinop( function(m, n) { return m === n; }, function(m, n) { return bnEquals.call(m, n); }, {doNotCoerseToFloating: true}); // _integerGreaterThan: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThan = makeIntegerBinop( function(m, n) { return m > n; }, function(m, n) { return bnCompareTo.call(m, n) > 0; }, {doNotCoerseToFloating: true}); // _integerLessThan: integer-scheme-number integer-scheme-number -> boolean var _integerLessThan = makeIntegerBinop( function(m, n) { return m < n; }, function(m, n) { return bnCompareTo.call(m, n) < 0; }, {doNotCoerseToFloating: true}); // _integerGreaterThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerGreaterThanOrEqual = makeIntegerBinop( function(m, n) { return m >= n; }, function(m, n) { return bnCompareTo.call(m, n) >= 0; }, {doNotCoerseToFloating: true}); // _integerLessThanOrEqual: integer-scheme-number integer-scheme-number -> boolean var _integerLessThanOrEqual = makeIntegerBinop( function(m, n) { return m <= n; }, function(m, n) { return bnCompareTo.call(m, n) <= 0; }, {doNotCoerseToFloating: true}); ////////////////////////////////////////////////////////////////////// // The boxed number types are expected to implement the following // interface. // // toString: -> string // level: number // liftTo: scheme-number -> scheme-number // isFinite: -> boolean // isInteger: -> boolean // Produce true if this number can be coersed into an integer. // isRational: -> boolean // Produce true if the number is rational. // isReal: -> boolean // Produce true if the number is real. // isExact: -> boolean // Produce true if the number is exact // toExact: -> scheme-number // Produce an exact number. // toFixnum: -> javascript-number // Produce a javascript number. // greaterThan: scheme-number -> boolean // Compare against instance of the same type. // greaterThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // lessThan: scheme-number -> boolean // Compare against instance of the same type. // lessThanOrEqual: scheme-number -> boolean // Compare against instance of the same type. // add: scheme-number -> scheme-number // Add with an instance of the same type. // subtract: scheme-number -> scheme-number // Subtract with an instance of the same type. // multiply: scheme-number -> scheme-number // Multiply with an instance of the same type. // divide: scheme-number -> scheme-number // Divide with an instance of the same type. // numerator: -> scheme-number // Return the numerator. // denominator: -> scheme-number // Return the denominator. // integerSqrt: -> scheme-number // Produce the integer square root. // sqrt: -> scheme-number // Produce the square root. // abs: -> scheme-number // Produce the absolute value. // floor: -> scheme-number // Produce the floor. // ceiling: -> scheme-number // Produce the ceiling. // conjugate: -> scheme-number // Produce the conjugate. // magnitude: -> scheme-number // Produce the magnitude. @@ -1161,1025 +1162,1025 @@ if (! this['plt']['lib']['Numbers']) { Rational.prototype.toFixnum = function() { return _integerDivideToFixnum(this.n, this.d); }; Rational.prototype.numerator = function() { return this.n; }; Rational.prototype.denominator = function() { return this.d; }; // FIXME: up to this point I've modified Rational to use the _integer functions. // I need to fix up the rest of Rational. Rational.prototype.greaterThan = function(other) { return _integerGreaterThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.greaterThanOrEqual = function(other) { return _integerGreaterThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThan = function(other) { return _integerLessThan(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.lessThanOrEqual = function(other) { return _integerLessThanOrEqual(_integerMultiply(this.n, other.d), _integerMultiply(this.d, other.n)); }; Rational.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Rational.prototype.sqrt = function() { if (_integerGreaterThanOrEqual(this.n, 0)) { var newN = sqrt(this.n); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Rational.makeInstance(newN, newD); } else { return FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD)); } } else { var newN = sqrt(negate(this.n)); var newD = sqrt(this.d); if (equals(floor(newN), newN) && equals(floor(newD), newD)) { return Complex.makeInstance( 0, Rational.makeInstance(newN, newD)); } else { return Complex.makeInstance( 0, FloatPoint.makeInstance(_integerDivideToFixnum(newN, newD))); } } }; Rational.prototype.abs = function() { return Rational.makeInstance(abs(this.n), this.d); }; Rational.prototype.floor = function() { return fromFixnum(Math.floor(this.n / this.d)); }; Rational.prototype.ceiling = function() { return fromFixnum(Math.ceil(this.n / this.d)); }; Rational.prototype.conjugate = function() { return this; }; Rational.prototype.magnitude = Rational.prototype.abs; Rational.prototype.log = function(){ return FloatPoint.makeInstance(Math.log(this.n / this.d)); }; Rational.prototype.angle = function(){ if (_integerIsZero(this.n)) return 0; if (_integerGreaterThan(this.n, 0)) return 0; else return FloatPoint.pi; }; Rational.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.expt = function(a){ return FloatPoint.makeInstance(Math.pow(_integerDivideToFixnum(this.n, this.d), _integerDivideToFixnum(a.n, a.d))); }; Rational.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(_integerDivideToFixnum(this.n, this.d))); }; Rational.prototype.imaginaryPart = function(){ return 0; }; Rational.prototype.realPart = function(){ return this; }; Rational.prototype.round = function() { // FIXME: not correct when values are bignums if (equals(this.d, 2)) { // Round to even if it's a n/2 var v = _integerDivideToFixnum(this.n, this.d); var fl = Math.floor(v); var ce = Math.ceil(v); if (_integerIsZero(fl % 2)) { return fromFixnum(fl); } else { return fromFixnum(ce); } } else { return fromFixnum(Math.round(this.n / this.d)); } }; var _rationalCache = {}; Rational.makeInstance = function(n, d) { if (n === undefined) throwRuntimeError("n undefined", n, d); if (d === undefined) { d = 1; } if (_integerLessThan(d, 0)) { n = negate(n); d = negate(d); } var divisor = _integerGcd(abs(n), abs(d)); n = _integerQuotient(n, divisor); d = _integerQuotient(d, divisor); // Optimization: if we can get around construction the rational // in favor of just returning n, do it: if (_integerIsOne(d) || _integerIsZero(n)) { return n; } return new Rational(n, d); }; // _rationalCache = {}; // (function() { // var i; // for(i = -500; i < 500; i++) { // _rationalCache[i] = new Rational(i, 1); // } // })(); // Rational.NEGATIVE_ONE = new Rational(-1, 1); // Rational.ZERO = new Rational(0, 1); // Rational.ONE = new Rational(1, 1); // Rational.TWO = new Rational(2, 1); // Floating Point numbers var FloatPoint = function(n) { this.n = n; }; FloatPoint = FloatPoint; var NaN = new FloatPoint(Number.NaN); var inf = new FloatPoint(Number.POSITIVE_INFINITY); var neginf = new FloatPoint(Number.NEGATIVE_INFINITY); // We use these two constants to represent the floating-point coersion // of bignums that can't be represented with fidelity. var TOO_POSITIVE_TO_REPRESENT = new FloatPoint(Number.POSITIVE_INFINITY); var TOO_NEGATIVE_TO_REPRESENT = new FloatPoint(Number.NEGATIVE_INFINITY); // Negative zero is a distinguished value representing -0.0. // There should only be one instance for -0.0. var NEGATIVE_ZERO = new FloatPoint(0); FloatPoint.pi = new FloatPoint(Math.PI); FloatPoint.e = new FloatPoint(Math.E); FloatPoint.nan = NaN; FloatPoint.inf = inf; FloatPoint.neginf = neginf; FloatPoint.makeInstance = function(n) { if (isNaN(n)) { return FloatPoint.nan; } else if (n === Number.POSITIVE_INFINITY) { return FloatPoint.inf; } else if (n === Number.NEGATIVE_INFINITY) { return FloatPoint.neginf; } return new FloatPoint(n); }; FloatPoint.prototype.isFinite = function() { return (isFinite(this.n) || this === TOO_POSITIVE_TO_REPRESENT || this === TOO_NEGATIVE_TO_REPRESENT); }; FloatPoint.prototype.toExact = function() { // The precision of ieee is about 16 decimal digits, which we use here. if (! isFinite(this.n) || isNaN(this.n)) { throwRuntimeError("toExact: no exact representation for " + this, this); } var fracPart = this.n - Math.floor(this.n); var intPart = this.n - fracPart; return add(intPart, Rational.makeInstance(Math.floor(fracPart * 10e16), 10e16)); }; FloatPoint.prototype.isExact = function() { return false; }; FloatPoint.prototype.level = 2; FloatPoint.prototype.liftTo = function(target) { if (target.level === 3) return new Complex(this, 0); return throwRuntimeError("invalid level of Number", this, target); }; FloatPoint.prototype.toString = function() { if (isNaN(this.n)) return "+nan.0"; if (this.n === Number.POSITIVE_INFINITY) return "+inf.0"; if (this.n === Number.NEGATIVE_INFINITY) return "-inf.0"; if (this === NEGATIVE_ZERO) return "-0.0"; if (this.n === 0) return "0.0"; return this.n.toString(); }; FloatPoint.prototype.equals = function(other, aUnionFind) { return ((other instanceof FloatPoint) && ((this.n === other.n))); }; FloatPoint.prototype.isRational = function() { return this.isFinite(); }; FloatPoint.prototype.isInteger = function() { return this.isFinite() && this.n === Math.floor(this.n); }; FloatPoint.prototype.isReal = function() { return true; }; // sign: Number -> {-1, 0, 1} var sign = function(n) { if (lessThan(n, 0)) { return -1; } else if (greaterThan(n, 0)) { return 1; } else if (n === NEGATIVE_ZERO) { return -1; } else { return 0; } }; FloatPoint.prototype.add = function(other) { if (this.isFinite() && other.isFinite()) { if (this === NEGATIVE_ZERO && other === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(this.n + other.n); } else { if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (this.isFinite() && ! other.isFinite()) { return other; } else if (!this.isFinite() && other.isFinite()) { return this; } else { return ((sign(this) * sign(other) === 1) ? this : NaN); }; } }; FloatPoint.prototype.subtract = function(other) { if (this.isFinite() && other.isFinite()) { var result = this.n - other.n; if (result === 0.0) { if (other.n === NEGATIVE_ZERO) { return FloatPoint.makeInstance(result); } else if (this.n === NEGATIVE_ZERO) { return NEGATIVE_ZERO; } } return FloatPoint.makeInstance(result); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && ! other.isFinite()) { if (sign(this) === sign(other)) { return NaN; } else { return this; } } else if (this.isFinite()) { return multiply(other, -1); } else { // other.isFinite() return this; } }; FloatPoint.prototype.negate = function() { if (this === NEGATIVE_ZERO) { return FloatPoint.makeInstance(0); } else if (this.n === 0) { return NEGATIVE_ZERO; } return FloatPoint.makeInstance(-this.n); }; FloatPoint.prototype.multiply = function(other) { if (this.n === 0 || other.n === 0) { return FloatPoint.makeInstance(0.0); } if (this.isFinite() && other.isFinite()) { var product = this.n * other.n; if (product !== 0) { return FloatPoint.makeInstance(product); } return sign(this) * sign(other) == 1 ? FloatPoint.makeInstance(0) : NEGATIVE_ZERO; } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else { return ((sign(this) * sign(other) === 1) ? inf : neginf); } }; FloatPoint.prototype.divide = function(other) { if (this.isFinite() && other.isFinite()) { if (other.n === 0) { return throwRuntimeError("division by zero", this, other); } return FloatPoint.makeInstance(this.n / other.n); } else if (isNaN(this.n) || isNaN(other.n)) { return NaN; } else if (! this.isFinite() && !other.isFinite()) { return NaN; } else if (this.isFinite() && !other.isFinite()) { return FloatPoint.makeInstance(0.0); } else if (! this.isFinite() && other.isFinite()) { return ((sign(this) * sign(other) === 1) ? inf : neginf); } else { return throwRuntimeError("impossible", this, other); } }; FloatPoint.prototype.toFixnum = function() { return this.n; }; FloatPoint.prototype.numerator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(parseFloat(match[1] + match[2])); } else { return this; } }; FloatPoint.prototype.denominator = function() { var stringRep = this.n.toString(); var match = stringRep.match(/^(.*)\.(.*)$/); if (match) { return FloatPoint.makeInstance(Math.pow(10, match[2].length)); } else { return FloatPoint.makeInstance(1.0); } }; FloatPoint.prototype.floor = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.floor(this.n)); }; FloatPoint.prototype.ceiling = function() { if (! isFinite(this.n)) { return this; } return fromFixnum(Math.ceil(this.n)); }; FloatPoint.prototype.greaterThan = function(other) { return this.n > other.n; }; FloatPoint.prototype.greaterThanOrEqual = function(other) { return this.n >= other.n; }; FloatPoint.prototype.lessThan = function(other) { return this.n < other.n; }; FloatPoint.prototype.lessThanOrEqual = function(other) { return this.n <= other.n; }; FloatPoint.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; FloatPoint.prototype.sqrt = function() { if (this.n < 0) { var result = Complex.makeInstance( 0, FloatPoint.makeInstance(Math.sqrt(-this.n))); return result; } else { return FloatPoint.makeInstance(Math.sqrt(this.n)); } }; FloatPoint.prototype.abs = function() { return FloatPoint.makeInstance(Math.abs(this.n)); }; FloatPoint.prototype.log = function(){ if (this.n < 0) - return log(Complex.makeInstance(this, 0)); + return (new Complex(this, 0)).log(); else return FloatPoint.makeInstance(Math.log(this.n)); }; FloatPoint.prototype.angle = function(){ if (0 === this.n) return 0; if (this.n > 0) return 0; else return FloatPoint.pi; }; FloatPoint.prototype.tan = function(){ return FloatPoint.makeInstance(Math.tan(this.n)); }; FloatPoint.prototype.atan = function(){ return FloatPoint.makeInstance(Math.atan(this.n)); }; FloatPoint.prototype.cos = function(){ return FloatPoint.makeInstance(Math.cos(this.n)); }; FloatPoint.prototype.sin = function(){ return FloatPoint.makeInstance(Math.sin(this.n)); }; FloatPoint.prototype.expt = function(a){ if (this.n === 1) { if (a.isFinite()) { return this; } else if (isNaN(a.n)){ return this; } else { return this; } } else { return FloatPoint.makeInstance(Math.pow(this.n, a.n)); } }; FloatPoint.prototype.exp = function(){ return FloatPoint.makeInstance(Math.exp(this.n)); }; FloatPoint.prototype.acos = function(){ return FloatPoint.makeInstance(Math.acos(this.n)); }; FloatPoint.prototype.asin = function(){ return FloatPoint.makeInstance(Math.asin(this.n)); }; FloatPoint.prototype.imaginaryPart = function(){ return 0; }; FloatPoint.prototype.realPart = function(){ return this; }; FloatPoint.prototype.round = function(){ if (isFinite(this.n)) { if (Math.abs(Math.floor(this.n) - this.n) === 0.5) { if (Math.floor(this.n) % 2 === 0) return fromFixnum(Math.floor(this.n)); return fromFixnum(Math.ceil(this.n)); } else { return fromFixnum(Math.round(this.n)); } } else { return this; } }; FloatPoint.prototype.conjugate = function() { return this; }; FloatPoint.prototype.magnitude = FloatPoint.prototype.abs; ////////////////////////////////////////////////////////////////////// // Complex numbers ////////////////////////////////////////////////////////////////////// var Complex = function(r, i){ this.r = r; this.i = i; }; // Constructs a complex number from two basic number r and i. r and i can // either be plt.type.Rational or plt.type.FloatPoint. Complex.makeInstance = function(r, i){ if (i === undefined) { i = 0; } if (typeof(r) === 'number') { r = fromFixnum(r); } if (typeof(i) === 'number') { i = fromFixnum(i); } if (isExact(i) && isInteger(i) && _integerIsZero(i)) { return r; } return new Complex(r, i); }; Complex.prototype.toString = function() { var realPart = this.r.toString(), imagPart = this.i.toString(); if (imagPart[0] === '-' || imagPart[0] === '+') { return realPart + imagPart + 'i'; } else { return realPart + "+" + imagPart + 'i'; } }; Complex.prototype.isFinite = function() { return isSchemeNumberFinite(this.r) && isSchemeNumberFinite(this.i); }; Complex.prototype.isRational = function() { return isRational(this.r) && equals(this.i, 0); }; Complex.prototype.isInteger = function() { return (isInteger(this.r) && equals(this.i, 0)); }; Complex.prototype.toExact = function() { if (! this.isReal()) { throwRuntimeError("inexact->exact: expects argument of type real number", this); } return toExact(this.r); }; Complex.prototype.isExact = function() { return isExact(this.r) && isExact(this.i); }; Complex.prototype.level = 3; Complex.prototype.liftTo = function(target){ throwRuntimeError("Don't know how to lift Complex number", this, target); }; Complex.prototype.equals = function(other) { var result = ((other instanceof Complex) && (equals(this.r, other.r)) && (equals(this.i, other.i))); return result; }; Complex.prototype.greaterThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">: expects argument of type real number", this, other); } return greaterThan(this.r, other.r); }; Complex.prototype.greaterThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError(">=: expects argument of type real number", this, other); } return greaterThanOrEqual(this.r, other.r); }; Complex.prototype.lessThan = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<: expects argument of type real number", this, other); } return lessThan(this.r, other.r); }; Complex.prototype.lessThanOrEqual = function(other) { if (! this.isReal() || ! other.isReal()) { throwRuntimeError("<=: expects argument of type real number", this, other); } return lessThanOrEqual(this.r, other.r); }; Complex.prototype.abs = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("abs: expects argument of type real number", this); return abs(this.r); }; Complex.prototype.toFixnum = function(){ if (!equals(this.i, 0).valueOf()) throwRuntimeError("toFixnum: expects argument of type real number", this); return toFixnum(this.r); }; Complex.prototype.numerator = function() { if (!this.isReal()) throwRuntimeError("numerator: can only be applied to real number", this); return numerator(this.n); }; Complex.prototype.denominator = function() { if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return denominator(this.n); }; Complex.prototype.add = function(other){ return Complex.makeInstance( add(this.r, other.r), add(this.i, other.i)); }; Complex.prototype.subtract = function(other){ return Complex.makeInstance( subtract(this.r, other.r), subtract(this.i, other.i)); }; Complex.prototype.negate = function() { return Complex.makeInstance(negate(this.r), negate(this.i)); }; Complex.prototype.multiply = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( multiply(this.r, other.r), multiply(this.i, other.r)); } var r = subtract( multiply(this.r, other.r), multiply(this.i, other.i)); var i = add( multiply(this.r, other.i), multiply(this.i, other.r)); return Complex.makeInstance(r, i); }; Complex.prototype.divide = function(other){ // If the other value is real, just do primitive division if (other.isReal()) { return Complex.makeInstance( divide(this.r, other.r), divide(this.i, other.r)); } var con = conjugate(other); var up = multiply(this, con); // Down is guaranteed to be real by this point. var down = multiply(other, con); var result = Complex.makeInstance( divide(realPart(up), down), divide(imaginaryPart(up), down)); return result; }; Complex.prototype.conjugate = function(){ var result = Complex.makeInstance( this.r, subtract(0, this.i)); return result; }; Complex.prototype.magnitude = function(){ var sum = add( multiply(this.r, this.r), multiply(this.i, this.i)); return sqrt(sum); }; Complex.prototype.isReal = function(){ return equals(this.i, 0); }; Complex.prototype.integerSqrt = function() { var result = sqrt(x); if (isRational(result)) { return toExact(floor(result)); } else if (isReal(result)) { return toExact(floor(result)); } else { return Complex.makeInstance(toExact(floor(realPart(result))), toExact(floor(imaginaryPart(result)))); } }; Complex.prototype.sqrt = function(){ if (this.isReal()) return sqrt(this.r); // http://en.wikipedia.org/wiki/Square_root#Square_roots_of_negative_and_complex_numbers var r_plus_x = add(this.magnitude(), this.r); var r = sqrt(halve(r_plus_x)); var i = divide(this.i, sqrt(multiply(r_plus_x, FloatPoint.makeInstance(2)))); return Complex.makeInstance(r, i); }; Complex.prototype.log = function(){ var m = this.magnitude(); var theta = this.angle(); var result = add( log(m), timesI(theta)); return result; }; Complex.prototype.angle = function(){ if (this.isReal()) { return angle(this.r); } if (equals(0, this.r)) { var tmp = halve(FloatPoint.pi); return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { var tmp = atan(divide(abs(this.i), abs(this.r))); if (greaterThan(this.r, 0)) { return greaterThan(this.i, 0) ? tmp : negate(tmp); } else { return greaterThan(this.i, 0) ? subtract(FloatPoint.pi, tmp) : subtract(tmp, FloatPoint.pi); } } }; var plusI = Complex.makeInstance(0, 1); var minusI = Complex.makeInstance(0, -1); Complex.prototype.tan = function() { return divide(this.sin(), this.cos()); }; Complex.prototype.atan = function(){ if (equals(this, plusI) || equals(this, minusI)) { return neginf; } return multiply( plusI, multiply( FloatPoint.makeInstance(0.5), log(divide( add(plusI, this), add( plusI, subtract(0, this)))))); }; Complex.prototype.cos = function(){ if (this.isReal()) return cos(this.r); var iz = timesI(this); var iz_negate = negate(iz); return halve(add(exp(iz), exp(iz_negate))); }; Complex.prototype.sin = function(){ if (this.isReal()) return sin(this.r); var iz = timesI(this); var iz_negate = negate(iz); var z2 = Complex.makeInstance(0, Rational.TWO); var exp_negate = subtract(exp(iz), exp(iz_negate)); var result = divide(exp_negate, z2); return result; }; Complex.prototype.expt= function(y){ var expo = multiply(y, this.log()); return exp(expo); }; Complex.prototype.exp = function(){ var r = exp(this.r); var cos_a = cos(this.i); var sin_a = sin(this.i); return multiply( r, add(cos_a, timesI(sin_a))); }; Complex.prototype.acos = function(){ if (this.isReal()) return acos(this.r); var pi_half = halve(FloatPoint.pi); var iz = timesI(this); var root = sqrt(subtract(1, sqr(this))); var l = timesI(log(add(iz, root))); return add(pi_half, l); }; Complex.prototype.asin = function(){ if (this.isReal()) return asin(this.r); var oneNegateThisSq = subtract( 1, sqr(this)); var sqrtOneNegateThisSq = sqrt(oneNegateThisSq); return multiply( Rational.TWO, atan(divide( this, add( 1, sqrtOneNegateThisSq)))); }; Complex.prototype.ceiling = function(){ if (!this.isReal()) throwRuntimeError("ceiling: can only be applied to real number", this); return ceiling(this.r); }; Complex.prototype.floor = function(){ if (!this.isReal()) throwRuntimeError("floor: can only be applied to real number", this); return floor(this.r); }; Complex.prototype.imaginaryPart = function(){ return this.i; }; Complex.prototype.realPart = function(){ return this.r; }; Complex.prototype.round = function(){ if (!this.isReal()) throwRuntimeError("round: can only be applied to real number", this); return round(this.r); }; var rationalRegexp = new RegExp("^([+-]?\\d+)/(\\d+)$"); var bignumScientificPattern = new RegExp("^([+-]?\\d*)\\.?(\\d*)[Ee](\\+?\\d+)$"); var complexRegexp = new RegExp("^([+-]?[\\d\\w/\\.]*)([+-])([\\d\\w/\\.]*)i$"); var flonumRegexp = new RegExp("^([+-]?\\d*)\\.?(\\d*)$"); // fromString: string -> (scheme-number | false) var fromString = function(x) { var aMatch = x.match(rationalRegexp); if (aMatch) { return makeRational(fromString(aMatch[1]), fromString(aMatch[2])); } var cMatch = x.match(complexRegexp); if (cMatch) { return makeComplex(fromString(cMatch[1] || "0"), fromString(cMatch[2] + (cMatch[3] || "1"))); } if (x === '+nan.0' || x === '-nan.0') return FloatPoint.nan; if (x === '+inf.0') return FloatPoint.inf; if (x === '-inf.0') return FloatPoint.neginf; if (x === "-0.0") { return NEGATIVE_ZERO; } if (x.match(flonumRegexp) || x.match(bignumScientificPattern)) { var n = Number(x); if (isOverflow(n)) { return makeBignum(x); } else { return fromFixnum(n); } } else { return false; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // The code below comes from Tom Wu's BigInteger implementation: diff --git a/test/tests.js b/test/tests.js index 494371c..f92c42d 100644 --- a/test/tests.js +++ b/test/tests.js @@ -2207,1048 +2207,1037 @@ describe('sin', { // FIXME: we're missing this } }); describe('tan', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('acos', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('asin', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('imaginaryPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('realPart', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('round', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('exp', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('sqr', { 'fixnums': function() { // FIXME: add test case where value needs to become a bignum. assertTrue(eqv(sqr(42), 1764)); assertTrue(eqv(sqr(0), 0)); assertTrue(eqv(sqr(1), 1)); assertTrue(eqv(sqr(2), 4)); assertTrue(eqv(sqr(-1), 1)); assertTrue(eqv(sqr(-2), 4)); assertTrue(eqv(sqr(-12349), 152497801)); }, 'fixnum overflows to bignum': function() { var x = fromFixnum(2); for(var i = 0; i < 10; i++) { x = sqr(x); } // Basically, computing (expt 2 (expt 2 10)) assertTrue(eqv(x, makeBignum("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"))); }, 'bignums': function() { assertTrue(eqv(sqr(makeBignum("1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); assertTrue(eqv(sqr(makeBignum("-1297684398542133568912839")), makeBignum("1683984798219658952314406790914015952992379039921"))); }, 'rationals': function() { assertTrue(eqv(sqr(makeRational(1, 2)), makeRational(1, 4))); assertTrue(eqv(sqr(makeRational(-1, 7)), makeRational(1, 49))); assertTrue(eqv(sqr(makeRational(makeBignum("-1297684398542133568912839"), 5)), makeRational(makeBignum("1683984798219658952314406790914015952992379039921"), 25))); }, 'floats': function() { assertTrue(eqv(sqr(makeFloat(0.0)), makeFloat(0.0))); assertTrue(eqv(sqr(makeFloat(.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(makeFloat(-.25)), makeFloat(0.0625))); assertTrue(eqv(sqr(nan), nan)); assertTrue(eqv(sqr(inf), inf)); assertTrue(eqv(sqr(negative_inf), inf)); assertTrue(eqv(sqr(negative_zero), makeFloat(0.0))); }, 'complex': function() { assertTrue(eqv(sqr(negative_i), -1)); assertTrue(eqv(sqr(i), -1)); } }); describe('gcd', { 'fixnum / fixnum' : function() { // FIXME: we're missing this }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('lcm', { 'fixnum / fixnum' : function() { // FIXME: add test case where value needs to become a bignum. }, 'fixnum / bignum': function() { // FIXME: we're missing this }, 'bignum / bignum' : function() { // FIXME: we're missing this }, 'bignum / rational': function() { // FIXME: we're missing this }, 'bignum / float' : function() { // FIXME: we're missing this }, 'bignum / complex' : function() { // FIXME: we're missing this }, 'fixnum / rational' : function() { // FIXME: we're missing this }, 'fixnum / floating' : function() { // FIXME: we're missing this }, 'fixnum / complex' : function() { // FIXME: we're missing this }, 'rational / rational' : function() { // FIXME: we're missing this }, 'rational / floating' : function() { // FIXME: we're missing this }, 'rational / complex' : function() { // FIXME: we're missing this }, 'floating / floating' : function() { // FIXME: we're missing this }, 'floating / complex' : function() { // FIXME: we're missing this }, 'complex / complex' : function() { // FIXME: we're missing this } }); describe('integerSqrt', { 'fixnums': function() { // FIXME: we're missing this }, 'bignums': function() { // FIXME: we're missing this }, 'rationals': function() { // FIXME: we're missing this }, 'floats': function() { // FIXME: we're missing this }, 'complex': function() { // FIXME: we're missing this } }); describe('toString', { 'fixnums': function() { assertEquals("-123456789012345678901234567890", makeBignum("-123456789012345678901234567890").toString()); assertEquals("123456789012345678901234567890", makeBignum("123456789012345678901234567890").toString()); }, 'bignums': function() { assertEquals("0", makeBignum("0").toString()); assertEquals("-236579329853268932967423894623849289323568268954", makeBignum("-236579329853268932967423894623849289323568268954").toString()); assertEquals("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612", makeBignum("312981532653268913529653216935216851268932416843269129356216894159681236850432163527231684321782317892513672317605612").toString()); }, 'rationals': function() { assertEquals("1/2", makeRational(1, 2)); assertEquals("2398742368955236823956823968/239856325892398441", makeRational(makeBignum("2398742368955236823956823968"), makeBignum("239856325892398441"))); assertEquals("-2398742368955236823956823968/239856325892398441", makeRational(makeBignum("-2398742368955236823956823968"), makeBignum("239856325892398441"))); }, 'floats': function() { assertEquals('0.0', makeFloat(0).toString()); assertEquals('0.25', makeFloat(0.25).toString()); assertEquals('1.2354e+200', makeFloat(1.2354e200).toString()); assertEquals('1.2354e-200', makeFloat(1.2354e-200).toString()); assertEquals('-1.2354e-200', makeFloat(-1.2354e-200).toString()); assertEquals('-1', makeFloat(-1).toString()); assertEquals("+nan.0", nan.toString()); assertEquals("+inf.0", inf.toString()); assertEquals("-inf.0", negative_inf.toString()); assertEquals("-0.0", negative_zero.toString()); }, 'complex': function() { assertEquals("1+0.0i", makeComplex(1, makeFloat(0)).toString()); assertEquals("-1+0.0i", makeComplex(-1, makeFloat(0)).toString()); assertEquals("0+1i", makeComplex(0, 1).toString()); assertEquals("0-1i", makeComplex(0, -1).toString()); assertEquals("0-0.0i", makeComplex(0, negative_zero).toString()); assertEquals("3/4+5/6i", makeComplex(makeRational(3, 4), makeRational(5, 6)).toString()); assertEquals("3/4-5/6i", makeComplex(makeRational(3, 4), makeRational(-5, 6)).toString()); assertEquals("0.1-inf.0i", makeComplex(makeFloat(0.1), negative_inf).toString()); assertEquals("+nan.0+inf.0i", makeComplex(nan, inf).toString()); assertEquals("+nan.0+nan.0i", makeComplex(nan, nan).toString()); assertEquals("-inf.0-inf.0i", makeComplex(negative_inf, negative_inf).toString()); } }); describe('old tests from Moby Scheme', { testRationalReduction: function() { var n1 = makeRational(1,2); var n2 = makeRational(5, 10); var n3 = makeRational(5, 12); assertTrue(equals(n1, n2)); assertTrue(! equals(n2, n3)); }, testEqv: function() { assertTrue(eqv(nan, nan)); assertTrue(false == eqv(makeFloat(42), makeRational(42))); assertTrue(eqv(inf, inf)); assertTrue(eqv(negative_inf, negative_inf)); }, testEqual: function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.0); assertTrue(equals(n1, n2)); var n3 = makeComplex(makeRational(2),makeRational(0)); var n4 = makeComplex(makeRational(2),makeRational(1)); assertTrue(equals(n1, n3)); assertTrue(!equals(n3, n4)); assertTrue(equals(makeRational(1, 2), makeRational(2, 4))); assertTrue(false == equals(makeRational(1, 2), makeRational(2, 5))); assertTrue(false === equals(nan, nan)); assertTrue(false === equals(nan, makeRational(3))); assertTrue(false === equals(makeRational(3), nan)); }, testAbs : function(){ var n1 = makeRational(-2,1); var n2 = makeRational(4, 2); var n3 = makeComplex(makeRational(2), makeRational(0)); assertTrue(equals(abs(n1), n2)); assertTrue(equals(abs(n3), n2)); }, testAdd : function(){ assertTrue(equals(add(makeRational(2,1), makeRational(3,1)), makeRational(5,1))); assertTrue(equals(add(makeRational(2,1), makeFloat(2.1)), makeFloat(4.1))); assertTrue(equals(add(makeRational(2,1), makeComplex(makeRational(2), makeRational(2))), makeComplex(makeRational(4),makeRational(2)))); assertTrue(equals(add(makeFloat(3.1), makeComplex(makeRational(2),makeRational(2))), makeComplex(makeFloat(5.1), makeRational(2)))); assertTrue(equals(add(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(5),makeRational( 4)))); }, testDivisionByZero: function() { divide(1, 1); assertFails(function() { divide(1, 0); }); assertFails(function() { divide(makeFloat(1), 0); }); assertFails(function() { divide(makeFloat(1),makeFloat(0)); }); }, testAddFloats: function() { assertEquals(0.1, add(makeRational(0), makeFloat(0.1)).toFixnum()); }, testSubtract : function(){ assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeRational(3,1)), makeRational(-5,1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeFloat(2.1)), makeFloat(-4.1))); assertTrue(equals(subtract(subtract(0, makeRational(2,1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(-4),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeFloat(2.1)), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(-4.1),makeRational( -2)))); assertTrue(equals(subtract(subtract(0, makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(-5),makeRational( -4)))); }, testMultiply : function(){ assertTrue(equals(multiply(makeRational(2,1), makeRational(3,1)), makeRational(6,1))); assertTrue(equals(multiply(makeRational(2,1), makeFloat(2.1)), makeFloat(4.2))); assertTrue(equals(multiply(makeRational(2,1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeRational(4),makeRational(4)))); assertTrue(equals(multiply(makeFloat(2.1), makeComplex(makeRational(2),makeRational( 2))), makeComplex(makeFloat(4.2),makeFloat( 4.2)))); assertTrue(equals(multiply(makeComplex(makeRational(2),makeRational( 2)), makeComplex(makeRational(3),makeRational( 2))), makeComplex(makeRational(2),makeRational( 10)))); }, testDivide : function(){ var six = makeRational(6, 1); assertTrue(equals(divide(divide(six, makeRational(2,1)), makeRational(3,1)), 1)); assertTrue(equals(divide(divide(six, makeFloat(1.5)), makeFloat(4.0)), 1)); assertTrue(equals(divide(divide(makeFloat(150), makeComplex(makeRational(3),makeRational( 4))), makeComplex(makeRational(3),makeRational( -4))), six)); assertTrue(equals(divide(1, six), makeRational(1, 6))); }, testConjugate : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); - assertTrue(equals(n1, Kernel.conjugate(n1))); - assertTrue(equals(n2, Kernel.conjugate(n2))); - assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), Kernel.conjugate(makeComplex(makeRational(1),makeRational( -2))))); + assertTrue(equals(n1, conjugate(n1))); + assertTrue(equals(n2, conjugate(n2))); + assertTrue(equals(makeComplex(makeRational(1),makeRational( 2)), conjugate(makeComplex(makeRational(1),makeRational( -2))))); }, testMagnitude : function(){ var n1 = makeRational(2,1); var n2 = makeFloat(2.1); - assertTrue(equals(n1, Kernel.magnitude(n1))); - assertTrue(equals(n2, Kernel.magnitude(n2))); - assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), Kernel.magnitude(makeComplex(makeRational(3),makeRational( -4))))); + assertTrue(equals(n1, magnitude(n1))); + assertTrue(equals(n2, magnitude(n2))); + assertTrue(equals(makeComplex(makeRational(5),makeRational( 0)), magnitude(makeComplex(makeRational(3),makeRational( -4))))); }, testComparison : function(){ - assertTrue(Kernel._greaterthan_(makeRational(2,1), - makeRational(1,1), - [])); - assertTrue(Kernel._greaterthan_(makeFloat(2.1), - makeRational(2,1), [])); - assertTrue(Kernel._greaterthan__equal_(makeFloat(2.0), - makeRational(2,1), - [])); - assertTrue(Kernel._greaterthan__equal_(makeComplex(makeFloat(2.0),makeRational( 0)), - makeRational(2,1), - [])); + assertTrue(greaterThan(makeRational(2,1), + makeRational(1,1))); + assertTrue(greaterThan(makeFloat(2.1), + makeRational(2,1))); + assertTrue(greaterThanOrEqual(makeFloat(2.0), + makeRational(2,1))); + assertTrue(greaterThanOrEqual(makeComplex(makeFloat(2.0),makeRational( 0)), + makeRational(2,1))); - assertTrue(Kernel._lessthan_(makeRational(2), - makeRational(3), [])); + assertTrue(lessThan(makeRational(2), + makeRational(3))); - assertTrue(! Kernel._lessthan_(makeRational(3), - makeRational(2), [])); + assertTrue(! lessThan(makeRational(3), + makeRational(2))); }, - testComparisonTypes : function() { - assertFails(isTypeMismatch, - function() { - Kernel._lessthan_(2, 3, [])}); - assertFails(isTypeMismatch, - function() { - Kernel._greaterthan_("2", "3", [])}); - }, testComparisonMore: function() { - assertTrue(! Kernel._greaterthan_(makeRational(2), - makeRational(3), [])); + assertTrue(! greaterThan(makeRational(2), + makeRational(3))); - assertTrue(Kernel._greaterthan_(makeRational(3), - makeRational(2), [])); + assertTrue(greaterThan(makeRational(3), + makeRational(2))); - assertTrue(! Kernel._greaterthan_(makeRational(3), - makeRational(3), [])); + assertTrue(! greaterThan(makeRational(3), + makeRational(3))); - assertTrue(Kernel._lessthan__equal_(makeRational(17), - makeRational(17), [])); + assertTrue(lessThanOrEqual(makeRational(17), + makeRational(17))); - assertTrue(Kernel._lessthan__equal_(makeRational(16), - makeRational(17), [])); + assertTrue(lessThanOrEqual(makeRational(16), + makeRational(17))); - assertTrue(!Kernel._lessthan__equal_(makeRational(16), - makeRational(15), [])); - assertFails(isTypeMismatch, - function() { - Kernel._lessthan__equal_("2", "3", [])}); + assertTrue(!lessThanOrEqual(makeRational(16), + makeRational(15))); }, testComparison2 : function () { var num = makeRational(0, 1); var upper = makeRational(480, 1); - assertTrue(Kernel._lessthan_(makeRational(5, 1), - upper, [])); - assertTrue(Kernel._lessthan_(makeRational(6, 1), - upper, [])); - assertTrue(Kernel._lessthan_(makeRational(7, 1), - upper, [])); - assertTrue(Kernel._lessthan_(makeRational(8, 1), - upper, [])); - assertTrue(Kernel._lessthan_(makeRational(9, 1), - upper, [])); + assertTrue(lessThan(makeRational(5, 1), + upper)); + assertTrue(lessThan(makeRational(6, 1), + upper)); + assertTrue(lessThan(makeRational(7, 1), + upper)); + assertTrue(lessThan(makeRational(8, 1), + upper)); + assertTrue(lessThan(makeRational(9, 1), + upper)); for (var i = 0; i < 60; i++) { - assertTrue(Kernel._lessthan_ - (num, upper, [])); - num = add([num, 1]); + assertTrue(lessThan + (num, upper)); + num = add(num, 1); } }, testAtan : function(){ - assertTrue(equals(Kernel.atan(1, []), plt.Kernel.pi.half().half())); + assertTrue(equals(atan(1), divide(pi, 4))); }, testLog : function(){ - assertTrue(equals(Kernel.log(1), 0)); - assertTrue(equals(Kernel.log(makeComplex(makeRational(0),makeRational(1))), plt.Kernel.pi.toComplex().timesI().half())); - assertTrue(equals(Kernel.log(makeFloat(-1)), plt.Kernel.pi.toComplex().timesI())); + assertTrue(equals(log(1), 0)); + assertTrue(equals(log(makeComplex(makeRational(0),makeRational(1))), divide(multiply(pi, i), 2))); + assertTrue(equals(log(makeFloat(-1)), multiply(pi, i))); }, testAngle : function(){ - assertTrue(equals(Kernel.angle(makeComplex(makeRational(0),makeRational(1))), PI.half())); - assertTrue(equals(Kernel.angle(makeComplex(makeRational(1),makeRational(1))), PI.half().half())); - assertTrue(equals(Kernel.angle(makeFloat(-1)), PI)); - assertTrue(equals(Kernel.angle(makeComplex(makeRational(-1),makeRational( 1))), PI.multiply(makeFloat(0.75)))); - assertTrue(equals(Kernel.angle(makeComplex(makeRational(-1),makeRational( -1))), PI.multiply(makeFloat(-0.75)))); - assertTrue(equals(Kernel.angle(makeComplex(makeRational(1),makeRational( -1))), PI.half().half().minus())); + assertTrue(equals(angle(makeComplex(makeRational(0),makeRational(1))), divide(pi, 2))); + assertTrue(equals(angle(makeComplex(makeRational(1),makeRational(1))), divide(pi, 4))); + assertTrue(equals(angle(makeFloat(-1)), pi)); + assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( 1))), + multiply(pi, makeFloat(0.75)))); + assertTrue(equals(angle(makeComplex(makeRational(-1),makeRational( -1))), + multiply(pi, makeFloat(-0.75)))); + assertTrue(equals(angle(makeComplex(makeRational(1),makeRational( -1))), + multiply(pi, makeRational(-1, 4)))); }, testExp : function(){ assertTrue(equals(Kernel.exp(0), 1, [])); assertTrue(equals(Kernel.exp(1), Kernel.e, [])); assertTrue(equals_tilde_(Kernel.exp(makeRational(2)), Kernel.sqr(Kernel.e), makeFloat(0.0001))); }, testExpt : function(){ var i = plt.types.makeComplex( makeRational(0),makeRational( 1)); assertTrue(equals( Kernel.expt(i, i), Kernel.exp(PI.half().minus()))); assertTrue(equals( Kernel.expt(makeFloat(2), makeFloat(3)), makeFloat(8))); assertTrue(equals( Kernel.expt(makeComplex( makeRational(3,4), makeRational(7,8)), makeRational(2))), makeComplex(makeRational(-13, 64), makeRational(21, 16))); }, testSin : function(){ assertTrue(equals(Kernel.sin(divide(PI, makeFloat(2))), 1)); }, testCos : function(){ assertTrue(equals(Kernel.cos(0), 1)); }, testSqr: function() { var n1 = makeRational(42); assertEquals(1764, Kernel.sqr(n1).toFixnum()); assertFails(isTypeMismatch, function() { Kernel.sqr("42"); }); }, testIntegerSqrt: function() { var n1 = makeRational(36); var n2 = makeRational(6); assertEquals(n2, Kernel.integer_dash_sqrt(n1)); assertFails(function() { Kernel.integer_dash_sqrt(makeFloat(3.5)); }); }, testSqrt : function(){ assertTrue(equals(Kernel.sqrt(makeFloat(4)), makeFloat(2))); assertTrue(equals(Kernel.sqrt(makeFloat(-1)), makeComplex(makeRational(0),makeRational(1)))); }, testAcos : function(){ assertTrue(equals(Kernel.acos(1), 0)); assertTrue(equals(Kernel.acos(makeFloat(-1)), PI)); }, testAsin : function(){ assertTrue(equals( Kernel.asin(0), 0)); assertTrue(equals(Kernel.asin(-1), PI.half().minus())); assertTrue(equals( Kernel.asin(1), PI.half())); assertTrue(equals( Kernel.asin(makeRational(1, 4)), makeFloat(0.25268025514207865))); assertTrue(equals( Kernel.asin(makeComplex(1, 5)), makeComplex(0.1937931365549321, 2.3309746530493123))); }, testTan : function(){ assertTrue(equals(Kernel.tan(0), 0)); }, testComplex_question_ : function(){ assertTrue(Kernel.complex_question_(PI)); assertTrue(Kernel.complex_question_(1)); assertTrue(Kernel.complex_question_(makeFloat(2.718))); assertTrue(Kernel.complex_question_(makeComplex(0,1))); assertTrue(!Kernel.complex_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.complex_question_(String.makeInstance("hi"))); assertTrue(!Kernel.complex_question_(Symbol.makeInstance('h'))); }, testMakePolar : function() { assertTrue(equals(Kernel.make_dash_polar(makeRational(5), makeRational(0)), makeComplex(makeRational(5),makeRational( 0)))); var n = Kernel.make_dash_polar(makeRational(5), PI); var delta = makeFloat(0.0000001); assertTrue(equals_tilde_(Kernel.imag_dash_part(n), makeRational(0), delta)); assertTrue(equals_tilde_(Kernel.real_dash_part(n), makeRational(-5), delta)); }, testMakeRectangular: function() { assertTrue(equals(Kernel.make_dash_rectangular (makeRational(4), makeRational(3)), makeComplex(makeRational(4),makeRational( 3)))); assertTrue(equals(Kernel.make_dash_rectangular (makeRational(5), makeRational(4)), makeComplex(makeRational(5),makeRational( 4)))); }, testCosh : function(){ assertTrue(equals(Kernel.cosh(0), 1)); }, testSinh : function(){ assertTrue(equals(Kernel.sinh(0), 0)); }, testDenominator : function(){ assertTrue(equals(Kernel.denominator(makeRational(7,2)), makeRational(2,1))); assertTrue(equals(Kernel.denominator(makeFloat(3)), makeFloat(1))); }, testNumerator : function(){ assertTrue(equals(Kernel.numerator(makeRational(7,2)), makeRational(7,1))); assertTrue(equals(Kernel.numerator(makeFloat(3)), makeFloat(3))); }, testIsExact : function() { assertTrue(Kernel.exact_question_(makeRational(3))); assertTrue(! Kernel.exact_question_(makeFloat(3.0))); assertTrue(! Kernel.exact_question_(makeFloat(3.5))); }, testIsInexact : function() { assertTrue(! Kernel.inexact_question_(makeRational(3))); assertTrue(Kernel.inexact_question_(makeFloat(3.0))); assertTrue(Kernel.inexact_question_(makeFloat(3.5))); }, testExactToInexact : function() { assertTrue(equals(Kernel.exact_dash__greaterthan_inexact(makeRational(3)), makeFloat(3.0), [])); assertTrue(Kernel.inexact_question_(Kernel.exact_dash__greaterthan_inexact(makeRational(3)))); }, testInexactToExact : function() { assertTrue(equals(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)), makeRational(3), [])); assertTrue(Kernel.exact_question_(Kernel.inexact_dash__greaterthan_exact(makeFloat(3)))); }, testFloatsAreInexact: function() { assertTrue(! Kernel.exact_question_(makeFloat(3.0))); }, testOdd_question_ : function(){ assertTrue(Kernel.odd_question_(1)); assertTrue(! Kernel.odd_question_(0)); assertTrue(Kernel.odd_question_(makeFloat(1))); assertTrue(Kernel.odd_question_(makeComplex(makeRational(1),makeRational( 0)))); assertTrue(Kernel.odd_question_(makeRational(-1, 1))); }, testInfinityComputations : function() { assertTrue(equals(0, multiply([0, inf]), [])); }, testEven_question_ : function(){ assertTrue(Kernel.even_question_(0)); assertTrue(! Kernel.even_question_(1)); assertTrue(Kernel.even_question_(makeFloat(2))); assertTrue(Kernel.even_question_(makeComplex(makeRational(2),makeRational( 0)))); }, testPositive_question_ : function(){ assertTrue(Kernel.positive_question_(1)); assertTrue(!Kernel.positive_question_(0)); assertTrue(Kernel.positive_question_(makeFloat(1.1))); assertTrue(Kernel.positive_question_(makeComplex(makeRational(1),makeRational(0)))); }, testNegative_question_ : function(){ assertTrue(Kernel.negative_question_(makeRational(-5))); assertTrue(!Kernel.negative_question_(1)); assertTrue(!Kernel.negative_question_(0)); assertTrue(!Kernel.negative_question_(makeFloat(1.1))); assertTrue(!Kernel.negative_question_(makeComplex(makeRational(1),makeRational(0)))); }, testCeiling : function(){ assertTrue(equals(Kernel.ceiling(1), 1)); assertTrue(equals(Kernel.ceiling(PI), makeFloat(4))); assertTrue(equals(Kernel.ceiling(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(4))); }, testFloor : function(){ assertTrue(equals(Kernel.floor(1), 1)); assertTrue(equals(Kernel.floor(PI), makeFloat(3))); assertTrue(equals(Kernel.floor(makeComplex(makeFloat(3.1),makeRational(0))), makeFloat(3))); }, testImag_dash_part : function(){ assertTrue(equals(Kernel.imag_dash_part(1), 0)); assertTrue(equals(Kernel.imag_dash_part(PI), 0)); assertTrue(equals(Kernel.imag_dash_part(makeComplex(makeRational(0),makeRational(1))), 1)); }, testReal_dash_part : function(){ assertTrue(equals(Kernel.real_dash_part(1), 1)); assertTrue(equals(Kernel.real_dash_part(PI), PI)); assertTrue(equals(Kernel.real_dash_part(makeComplex(makeRational(0),makeRational(1))), 0)); }, testInteger_question_ : function(){ assertTrue(Kernel.integer_question_(1)); assertTrue(Kernel.integer_question_(makeFloat(3.0))); assertTrue(!Kernel.integer_question_(makeFloat(3.1))); assertTrue(Kernel.integer_question_(makeComplex(makeRational(3),makeRational(0)))); assertTrue(!Kernel.integer_question_(makeComplex(makeFloat(3.1),makeRational(0)))); }, testMake_dash_rectangular: function(){ assertTrue(equals(Kernel.make_dash_rectangular(1, 1), makeComplex(makeRational(1),makeRational(1)))); }, testMaxAndMin : function(){ var n1 = makeFloat(-1); var n2 = 0; var n3 = 1; var n4 = makeComplex(makeRational(4),makeRational(0)); assertTrue(equals(n4, Kernel.max(n1, [n2,n3,n4]))); assertTrue(equals(n1, Kernel.min(n1, [n2,n3,n4]))); var n5 = makeFloat(1.1); assertEquals(n5, Kernel.max(n1, [n2, n3, n5])); assertEquals(n1, Kernel.min(n2, [n3, n4, n5, n1])); }, testLcm : function () { assertTrue(equals(makeRational(12), Kernel.lcm(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); }, testGcd : function () { assertTrue(equals(makeRational(1), Kernel.gcd(makeRational(1), [makeRational(2), makeRational(3), makeRational(4)]))); assertTrue(equals(makeRational(5), Kernel.gcd(makeRational(100), [makeRational(5), makeRational(10), makeRational(25)]))); }, testIsRational : function() { assertTrue(Kernel.rational_question_(makeRational(42))); assertTrue(! Kernel.rational_question_(makeFloat(3.1415))); assertTrue(! Kernel.rational_question_("blah")); }, testNumberQuestion : function() { assertTrue(Kernel.number_question_(plt.types.makeRational(42))); assertTrue(Kernel.number_question_(42) == false); }, testNumber_dash__greaterthan_string : function(){ assertTrue(Kernel.string_equal__question_(String.makeInstance("1"), Kernel.number_dash__greaterthan_string(1),[])); assertTrue(!Kernel.string_equal__question_(String.makeInstance("2"), Kernel.number_dash__greaterthan_string(1),[])); assertEquals("5+0i", Kernel.number_dash__greaterthan_string(makeComplex(5, 0))); assertEquals("5+1i", Kernel.number_dash__greaterthan_string(makeComplex(5, 1))); assertEquals("4-2i", Kernel.number_dash__greaterthan_string(makeComplex(4, -2))); }, testQuotient : function(){ assertTrue(equals(Kernel.quotient(makeFloat(3), makeFloat(4)), 0)); assertTrue(equals(Kernel.quotient(makeFloat(4), makeFloat(3)), 1)); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(-36), makeRational(-7)), makeRational(5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(-7)), makeRational(-5))); assertTrue(equals( Kernel.quotient(makeRational(36), makeRational(7)), makeRational(5))); }, testRemainder : function(){ assertTrue(equals(Kernel.remainder(makeFloat(3), makeFloat(4)), makeFloat(3))); assertTrue(equals(Kernel.remainder(makeFloat(4), makeFloat(3)), makeFloat(1))); }, testModulo : function() { var n1 = makeRational(17); var n2 = makeRational(3); var n3 = makeRational(2); assertEquals(n3, Kernel.modulo(n1, n2)); assertEquals(n2, Kernel.modulo(n2, n1)); assertTrue(equals( makeRational(-3), Kernel.modulo(makeRational(13), makeRational(-4)))); assertTrue(equals( makeRational(3), Kernel.modulo(makeRational(-13), makeRational(4)))); assertTrue(equals( makeRational(-1), Kernel.modulo(makeRational(-13), makeRational(-4)))); assertTrue(equals( makeRational(0), Kernel.modulo(makeRational(4), makeRational(-2)))); }, testReal_question_ : function(){ assertTrue(Kernel.real_question_(PI)); assertTrue(Kernel.real_question_(1)); assertTrue(!Kernel.real_question_(makeComplex(makeRational(0),makeRational(1)))); assertTrue(Kernel.real_question_(makeComplex(makeRational(1),makeRational(0)))); assertTrue(!Kernel.real_question_(plt.types.Empty.EMPTY)); assertTrue(!Kernel.real_question_(String.makeInstance("hi"))); assertTrue(!Kernel.real_question_(Symbol.makeInstance('h'))); }, testRound : function(){ assertTrue(equals(Kernel.round(makeFloat(3.499999)), makeFloat(3))); assertTrue(equals(Kernel.round(makeFloat(3.5)), makeFloat(4))); assertTrue(equals(Kernel.round(makeFloat(3.51)), makeFloat(4))); assertTrue(equals(Kernel.round(makeRational(3)), makeRational(3))); assertTrue(equals(Kernel.round(makeRational(17, 4)), makeRational(4))); assertTrue(equals(Kernel.round(makeRational(-17, 4)), makeRational(-4))); }, testSgn : function(){ assertTrue(equals(Kernel.sgn(makeFloat(4)), 1)); assertTrue(equals(Kernel.sgn(makeFloat(-4)), Rational.NEGATIVE_ONE)); assertTrue(equals(Kernel.sgn(0), 0)); }, testZero_question_ : function(){ assertTrue(Kernel.zero_question_(0)); assertTrue(!Kernel.zero_question_(1)); assertTrue(Kernel.zero_question_(makeComplex(makeRational(0),makeRational(0)))); } });
bryanwoods/portfolio
a954842f3d1d469779ae499636425603d7a041a1
Adding new screenshot
diff --git a/screenshots/invitedtoourwedding/backend.png b/screenshots/invitedtoourwedding/backend.png index 3219e1b..40c1586 100644 Binary files a/screenshots/invitedtoourwedding/backend.png and b/screenshots/invitedtoourwedding/backend.png differ diff --git a/screenshots/invitedtoourwedding/screenshot.png b/screenshots/invitedtoourwedding/screenshot.png deleted file mode 100644 index dac4618..0000000 Binary files a/screenshots/invitedtoourwedding/screenshot.png and /dev/null differ
bryanwoods/portfolio
70de1b2483c833197842d4c58eca29c5f18cf17a
Updating screenshots
diff --git a/screenshots/invitedtoourwedding/backend.png b/screenshots/invitedtoourwedding/backend.png new file mode 100644 index 0000000..3219e1b Binary files /dev/null and b/screenshots/invitedtoourwedding/backend.png differ diff --git a/screenshots/invitedtoourwedding/frontend.png b/screenshots/invitedtoourwedding/frontend.png new file mode 100644 index 0000000..95b60bc Binary files /dev/null and b/screenshots/invitedtoourwedding/frontend.png differ diff --git a/screenshots/whothefrank/screenshot.png b/screenshots/whothefrank/screenshot.png index 2d5667b..9cd2d17 100644 Binary files a/screenshots/whothefrank/screenshot.png and b/screenshots/whothefrank/screenshot.png differ diff --git a/screenshots/wilsoncolab.com/screenshot.png b/screenshots/wilsoncolab.com/screenshot.png new file mode 100644 index 0000000..8425777 Binary files /dev/null and b/screenshots/wilsoncolab.com/screenshot.png differ