是否有任何数字可以对浮点数进行快速模数计算?

时间:2018-03-06 20:17:03

标签: c floating-point

我知道对于无符号整数,如果除数是2的幂,我可以用位掩码替换模运算。浮动数字是否有类似的属性?也就是说,是否有任何数字n可以比一般情况更有效地计算f mod n,而不一定使用位掩码?

当然,除了一个。 脑功能

编辑:澄清一下,f是任何浮点数(在运行时确定), n是任何格式的编译时常数,我希望结果是浮点数。

4 个答案:

答案 0 :(得分:3)

如果{ "extends": [ "eslint:recommended", "plugin:react/recommended" ], { "settings": { "react": { "createClass": "createReactClass", // Regex for Component Factory to use, // default to "createReactClass" "pragma": "React", // Pragma to use, default to "React" "version": "15.0", // React version, default to the latest React stable release "flowVersion": "0.53" // Flow version }, "propWrapperFunctions": [ "forbidExtraProps" ] // The names of any functions used to wrap the // propTypes object, e.g. `forbidExtraProps`. // If this isn't set, any propTypes wrapped in // a function will be skipped. } }, "env": { "browser": true, "node": true, "es6": true }, "globals": { "nconf": true }, "parser": "babel-eslint", "plugins": [ "react" ], "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "arrowFunctions": true, "binaryLiterals": true, "blockBindings": true, "classes": true, "defaultParams": true, "destructuring": true, "forOf": true, "generators": true, "modules": true, "objectLiteralComputedProperties": true, "objectLiteralDuplicateProperties": true, "objectLiteralShorthandMethods": true, "objectLiteralShorthandProperties": true, "octalLiterals": true, "regexUFlag": true, "regexYFlag": true, "spread": true, "superInFunctions": true, "templateStrings": true, "unicodeCodePointEscapes": true, "globalReturn": true, "jsx": true } }, "rules": { "react/jsx-uses-react": "error", "react/jsx-uses-vars": "error", // //Possible Errors // // The following rules point out areas where you might have made mistakes. // "comma-dangle": 2, // disallow or enforce trailing commas "no-cond-assign": 2, // disallow assignment in conditional expressions "no-console": ["error", { allow: ["warn", "error", "log"] }], // disallow use of console (off by default in the node environment) "no-constant-condition": 2, // disallow use of constant expressions in conditions "no-control-regex": 2, // disallow control characters in regular expressions "no-debugger": 2, // disallow use of debugger "no-dupe-args": 2, // disallow duplicate arguments in functions "no-dupe-keys": 2, // disallow duplicate keys when creating object literals "no-duplicate-case": 2, // disallow a duplicate case label. "no-empty": 2, // disallow empty statements "no-empty-character-class": 2, // disallow the use of empty character classes in regular expressions "no-ex-assign": 2, // disallow assigning to the exception in a catch block "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context "no-extra-parens": 0, // disallow unnecessary parentheses (off by default) "no-extra-semi": 2, // disallow unnecessary semicolons "no-func-assign": 2, // disallow overwriting functions written as function declarations "no-inner-declarations": 2, // disallow function or variable declarations in nested blocks "no-invalid-regexp": 2, // disallow invalid regular expression strings in the RegExp constructor "no-irregular-whitespace": 2, // disallow irregular whitespace outside of strings and comments "no-negated-in-lhs": 2, // disallow negation of the left operand of an in expression "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions "no-regex-spaces": 2, // disallow multiple spaces in a regular expression literal "quote-props": ["error", "consistent-as-needed"], // disallow reserved words being used as object literal keys (off by default) "no-sparse-arrays": 2, // disallow sparse arrays "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement "use-isnan": 2, // disallow comparisons with the value NaN "valid-jsdoc": 2, // Ensure JSDoc comments are valid (off by default) "valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string // // Best Practices // // These are rules designed to prevent you from making mistakes. // They either prescribe a better way of doing something or help you avoid footguns. // "block-scoped-var": 0, // treat var statements as if they were block scoped (off by default). 0: deep destructuring is not compatible https://github.com/eslint/eslint/issues/1863 "complexity": 0, // specify the maximum cyclomatic complexity allowed in a program (off by default) "consistent-return": 2, // require return statements to either always or never specify values "curly": 2, // specify curly brace conventions for all control statements "default-case": 2, // require default case in switch statements (off by default) "dot-notation": 2, // encourages use of dot notation whenever possible "eqeqeq": 2, // require the use of === and !== "guard-for-in": 2, // make sure for-in loops have an if statement (off by default) "no-alert": 2, // disallow the use of alert, confirm, and prompt "no-caller": 2, // disallow use of arguments.caller or arguments.callee "no-div-regex": 2, // disallow division operators explicitly at beginning of regular expression (off by default) "no-else-return": 2, // disallow else after a return in an if (off by default) "no-labels": 2, // disallow use of labels for anything other then loops and switches "no-eq-null": 2, // disallow comparisons to null without a type-checking operator (off by default) "no-eval": 2, // disallow use of eval() "no-extend-native": 2, // disallow adding to native types "no-extra-bind": 2, // disallow unnecessary function binding "no-fallthrough": 2, // disallow fallthrough of case statements "no-floating-decimal": 2, // disallow the use of leading or trailing decimal points in numeric literals (off by default) "no-implied-eval": 2, // disallow use of eval()-like methods "no-iterator": 2, // disallow usage of __iterator__ property "no-lone-blocks": 2, // disallow unnecessary nested blocks "no-loop-func": 2, // disallow creation of functions within loops "no-multi-spaces": 2, // disallow use of multiple spaces "no-multi-str": 2, // disallow use of multiline strings "no-native-reassign": 2, // disallow reassignments of native objects "no-new": 2, // disallow use of new operator when not part of the assignment or comparison "no-new-func": 2, // disallow use of new operator for Function object "no-new-wrappers": 2, // disallows creating new instances of String,Number, and Boolean "no-octal": 2, // disallow use of octal literals "no-octal-escape": 2, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251"; "no-param-reassign": 2, // disallow reassignment of function parameters (off by default) "no-process-env": 0, // disallow use of process.env (off by default) "no-proto": 2, // disallow usage of __proto__ property "no-redeclare": 2, // disallow declaring the same variable more then once "no-return-assign": 2, // disallow use of assignment in return statement "no-script-url": 2, // disallow use of javascript: urls. "no-self-compare": 2, // disallow comparisons where both sides are exactly the same (off by default) "no-sequences": 2, // disallow use of comma operator "no-throw-literal": 2, // restrict what can be thrown as an exception (off by default) "no-unused-expressions": 2, // disallow usage of expressions in statement position "no-void": 2, // disallow use of void operator (off by default) "no-warning-comments": [0, {"terms": ["todo", "fixme"], "location": "start"}], // disallow usage of configurable warning terms in comments": 2, // e.g. TODO or FIXME (off by default) "no-with": 2, // disallow use of the with statement "radix": 2, // require use of the second argument for parseInt() (off by default) "vars-on-top": 2, // requires to declare all vars on top of their containing scope (off by default) "wrap-iife": 2, // require immediate function invocation to be wrapped in parentheses (off by default) "yoda": 2, // require or disallow Yoda conditions // // Strict Mode // // These rules relate to using strict mode. // "strict": 0, // controls location of Use Strict Directives. 0: required by `babel-eslint` // // Variables // // These rules have to do with variable declarations. // "no-catch-shadow": 2, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment) "no-delete-var": 2, // disallow deletion of variables "no-label-var": 2, // disallow labels that share a name with a variable "no-shadow": 2, // disallow declaration of variables already declared in the outer scope "no-shadow-restricted-names": 2, // disallow shadowing of names such as arguments "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block "no-undef-init": 2, // disallow use of undefined when initializing variables "no-undefined": 2, // disallow use of undefined variable (off by default) "no-unused-vars": 2, // disallow declaration of variables that are not used in the code "no-use-before-define": 2, // disallow use of variables before they are defined // //Stylistic Issues // // These rules are purely matters of style and are quite subjective. // "indent": [1, 2], // this option sets a specific tab width for your code (off by default) "brace-style": 1, // enforce one true brace style (off by default) "camelcase": 0, // require camel case names "comma-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after comma "comma-style": [1, "last"], // enforce one true comma style (off by default) "consistent-this": [1, "_this"], // enforces consistent naming when capturing the current execution context (off by default) "eol-last": 1, // enforce newline at the end of file, with no multiple empty lines "func-names": 0, // require function expressions to have a name (off by default) "func-style": 0, // enforces use of function declarations or expressions (off by default) "key-spacing": [1, {"beforeColon": false, "afterColon": true}], // enforces spacing between keys and values in object literal properties "max-nested-callbacks": [1, 3], // specify the maximum depth callbacks can be nested (off by default) "new-cap": [1, {newIsCap: true, capIsNew: false}], // require a capital letter for constructors "new-parens": 1, // disallow the omission of parentheses when invoking a constructor with no arguments "newline-after-var": 0, // allow/disallow an empty newline after var statement (off by default) "no-array-constructor": 1, // disallow use of the Array constructor "no-inline-comments": 1, // disallow comments inline after code (off by default) "no-lonely-if": 1, // disallow if as the only statement in an else block (off by default) "no-mixed-spaces-and-tabs": 0, // disallow mixed spaces and tabs for indentation "no-multiple-empty-lines": [1, {"max": 2}], // disallow multiple empty lines (off by default) "no-nested-ternary": 1, // disallow nested ternary expressions (off by default) "no-new-object": 1, // disallow use of the Object constructor "no-spaced-func": 1, // disallow space between function identifier and application "no-ternary": 0, // disallow the use of ternary operators (off by default) "no-trailing-spaces": 1, // disallow trailing whitespace at the end of lines "no-underscore-dangle": 1, // disallow dangling underscores in identifiers "one-var": [1, "never"], // allow just one var statement per function (off by default) "operator-assignment": [1, "never"], // require assignment operator shorthand where possible or prohibit it entirely (off by default) "padded-blocks": [1, "never"], // enforce padding within blocks (off by default) "quotes": ["error", "single", { "allowTemplateLiterals": true }], // specify whether double or single quotes should be used "semi": [1, "never"], // require or disallow use of semicolons instead of ASI "semi-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after semicolons "sort-vars": 0, // sort variables within the same declaration block (off by default) "space-before-blocks": [1, "always"], // require or disallow space before blocks (off by default) "space-before-function-paren": [1, {"anonymous": "always", "named": "never"}], // require or disallow space before function opening parenthesis (off by default) "object-curly-spacing": [1, "always"], // require or disallow spaces inside brackets (off by default) "space-in-parens": [1, "never"], // require or disallow spaces inside parentheses (off by default) "space-infix-ops": ["error", {"int32Hint": false}], // require spaces around operators "keyword-spacing": [1, {"before": true}], // require a space after return, throw, and case "space-unary-ops": [1, {"words": true, "nonwords": false}], // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default) "spaced-comment": [1, "always"], // require or disallow a space immediately following the // in a line comment (off by default) "wrap-regex": 0, // require regex literals to be wrapped in parentheses (off by default) // // ECMAScript 6 // // These rules are only relevant to ES6 environments and are off by default. // "no-var": 2, // require let or const instead of var (off by default) "generator-star-spacing": [2, "before"], // enforce the spacing around the * in generator functions (off by default) // // Legacy // // The following rules are included for compatibility with JSHint and JSLint. // While the names of the rules may not match up with the JSHint/JSLint counterpart, // the functionality is the same. // "max-depth": [0, 3], // specify the maximum depth that blocks can be nested (off by default) "max-len": [2, 100, 2], // specify the maximum length of a line in your program (off by default) "max-params": [2, 5], // limits the number of parameters that can be used in the function declaration. (off by default) "max-statements": 0, // specify the maximum number of statement allowed in a function (off by default) "no-bitwise": 0, // disallow use of bitwise operators (off by default) "no-plusplus": 2, // disallow use of unary operators, ++ and -- (off by default) // // eslint-plugin-react // // React specific linting rules for ESLint // "react/display-name": 0, // Prevent missing displayName in a React component definition "jsx-quotes": ["error", "prefer-single"], // Enforce quote style for JSX attributes "react/jsx-no-undef": 2, // Disallow undeclared variables in JSX "react/jsx-sort-props": 0, // Enforce props alphabetical sorting "react/jsx-uses-react": 2, // Prevent React to be incorrectly marked as unused "react/jsx-uses-vars": 2, // Prevent variables used in JSX to be incorrectly marked as unused "react/no-did-mount-set-state": 2, // Prevent usage of setState in componentDidMount "react/no-did-update-set-state": 2, // Prevent usage of setState in componentDidUpdate "react/no-multi-comp": 0, // Prevent multiple component definition per file "react/no-unknown-property": 2, // Prevent usage of unknown DOM property "react/react-in-jsx-scope": 2, // Prevent missing React when using JSX "react/self-closing-comp": 2, // Prevent extra closing tags for components without children "react/jsx-wrap-multilines": 2, // Prevent missing parentheses around multilines JSX //"react/prop-types": 2, // Prevent missing props validation in a React component definition } } n == 1.0,您可以执行以下操作:

n == -1.0

在x86_64上,trunc通常会使用r = f - trunc(f); 指令,因此速度非常快。

如果ROUNDSD是2的幂,其幅度大于或等于1,并且您的平台具有本地的fma函数(对于Intel,这意味着Haswell或更新),那么您可以吗

n

任何合理的编译器都应该将除法切换为乘法,并将否定值折叠为适当的FMA(或常量),从而产生乘法,截断和FMA。

这也适用于较小的2的幂,只要结果不会溢出(因此编译器不能自由替换它)。

任何编译器是否真的会这样做是另一回事。浮点余数函数使用不多,并且没有得到编译器编写者的太多关注,例如: https://bugs.llvm.org/show_bug.cgi?id=3359

答案 1 :(得分:2)

浮点类型的数学运算与整数类型的运算方式相同:如果 n 是基数的幂(二进制为2),那么 f modulo n 可以通过将表示值 n 或更大的数字(也称为高位或高位)归零来计算。

因此,对于b 15 b 14 b 13 b 12 b 的二进制整数> 11 b 10 b 9 b 8 b 7 b 6 b 5 b 4 b 3 b 2 b 1 b 0 ,我们可以简单地通过将b 15 设置为b 2 为零来计算模4的残差,只留下b 1 b <子> 0

类似地,如果浮点格式的基数是2,我们可以通过删除值为4或更大的所有数字来计算模4的残差。这不需要除法,但它确实需要检查表示值的位。仅仅一个简单的位掩码是不够的。

C标准将浮点类型表征为符号(±1),基数 b ,指数和一些基数 b 数字。因此,如果我们知道特定C实现用于表示浮点类型的格式(符号,指数和数字被编码为位的方式),则计算 f 模数的算法< em> n ,其中 n b 的力量,是:

  • y = f
  • 使用 y 的指数与 n 的指数之间的差异来确定 y 中的哪些数字的位置值小于名词
  • 将这些数字更改为零。
  • 返回 f - y

一些注意事项:

  • 算法必须处理无穷大,NaN,次正规和其他特殊情况。
  • 将副本 y 中的低位数归零并从 f 中减去而不是直接在 f 中将高位数归零的目的是为了避免需要将IEEE 754格式的隐含位置零。 (在所述算法中,如果 y 中的隐含位需要归零,则所有 y 都归零,因此很容易。)
  • 虽然没有使用除法,但操作并不像位掩码那样简单,一般不太可能有用。但是,有一些特殊情况,通常具有 d 的已知值和 x 的有限值,其中浮点表示的这种位操作很有用。

示例代码:

//  This code assumes double is IEEE 754 basic 64-bit binary floating-point.

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>


//  Return the bits representable double x.
static uint64_t Bits(double x)
    { return (union { double d; uint64_t u; }) { x } .u; }


//  Return the double represented by bits x.
static double Double(uint64_t x)
    { return (union { uint64_t u; double d; }) { x } .d; }


//  Return x modulo 2**E.
static double Mod(double x, int E)
{
    uint64_t b = Bits(x);
    int      e = b >> 52 & 0x7ff;

    //  If x is a NaN, return it.
    if (x != x) return x;

    //  Is x is infinite, return a NaN.
    if (!isfinite(x)) return NAN;

    //  If x is subnormal, adjust its exponent.
    if (e == 0) e = 1;

    //  Remove the encoding bias from e and get the difference in exponents.
    e = (e-1023) - E;

    //  Calculate number of bits to keep.  (Could be consolidated above, kept for illustration.)
    e = 52 - e;

    if (e <= 0) return 0;
    if (53 <= e) return x;

    //  Remove the low e bits (temporarily).
    b = b >> e << e;

    /*  Convert b to a double and subtract the bits we left in it from the
        original number, thus leaving the bits that were removed from b.
    */
    return x - Double(b);
}


static void Try(double x, int E)
{
    double expected = fmod(x, scalb(1, E));
    double observed = Mod(x, E);

    if (expected == observed)
        printf("Mod(%a, %d) = %a.\n", x, E, observed);
    else
    {
        printf("Error, Mod(%g, %d) = %g, but expected %g.\n",
            x, E, observed, expected);
        exit(EXIT_FAILURE);
    }
}


int main(void)
{
    double n = 4;

    //  Calculate the base-two logarithm of n.
    int E;
    frexp(n, &E);
    E -= 1;

    Try(7, E);
    Try(0x1p53 + 2, E);
    Try(0x1p53 + 6, E);
    Try(3.75, E);
    Try(-7, E);
    Try(0x1p-1049, E);
}

答案 2 :(得分:0)

一般来说,没有。然而,考虑到浮点的“模糊”性质(至少是IEEE 754),存在 abuses 技巧,可以通过近似从根本上加速某些计算,但代价是内存,精度,可移植性,可维护性,或这些的组合。

最简单的方法是预先计算操作并在运行时将结果存储到查找表中。你制作的桌子越大,你使用的内存就越多,但你也会获得更高的精确度。

更独特的方法涉及内存中的浮点表示。其中一个更着名的浮点攻击是fast inverse square root。通过这些概念,一般的想法是你可以为你想要的任何东西做一个近似函数,而不仅仅是反平方根。如果您知道输入范围和误差容差,则可以构建一个精确调整的算法。

如果不在基准测试中说明重要性,我将非常失职!如果您想要应用这些技术中的任何一种来加速您的计划,首先进行基准测试,并确保您正在优化正确的位置!

答案 3 :(得分:0)

是的,当它们是2的幂时,还有用伪掩码进行模运算的可能性,但在这种情况下,我们必须考虑浮动的事实点编号按照IEEE-754标准格式化。

让我们假设我们做同样的操作,但这次,由于数字是实数,两个数字的幂将是1位,后跟无限数量的0

1000000000000000000000000... * 2^exp

获取掩码,我们执行与整数相同的操作...将1更改为0,并将该数字后面的所有位更改为{ {1}}秒。

1

但这是一个全部掩码,因此除了超过模数的位(变为零)之外,永远不会触及尾数。当我们所有这些时,我们不需要做任何事情,只需将它们移到左边,让它们掉进废纸篓,因为它们被掩盖了。因此,尾数的屏蔽始终是左移(在数字的右边填充更多的数字--- oops,我们没有它们,所以填充零/随机位/ 1 ...)和然后标准化数字(这意味着将数字移位,直到第一个有意义的数字到达第一位并且指数偏差被协调调整)

让我们看一个例子:我们有0111111111111111111111111... * 2^exp = 1111111111111111111111111... * 2^(exp-1) (THIS NUMBER IS (1.0 - FLT_EPSILON) * 2^(exp_of_module - 1)) 作为模数,2.0M_PI)作为要屏蔽的数字:

3.141592...

3.141592... = 40 49 0f db = 0100 0000 0100 1001 0000 1111 1101 1011... ; which represents = 0 (positive) 100 0000 0 (exponent biased 128 ==> 1) (1.)100 1001 0000 1111 1101 1011... ^ Allways 1 so IEEE-754 doesn't include, we have to do, to operate. 11.00 1001 0000 1111 1101 1011... 01.11 1111 1111 1111 1111 1111... MASKED == 01.00 1001 0000 1111 1101 1011... / // //// //// //// //// ////,-- introduced to complete format RENORMALIZED == 1.001 0010 0001 1111 1011 011X... ; result = 0 (positive) = 011 1111 1 (new exponent after norm. 127 ==> 0) 1.001 0010 0001 1111 1011 011X = 0011 1111 1001 0010 0001 1111 1011 011X 符合预期。

如你所见,我们必须检查有偏差的指数之间的差异,并将尾数移动到该差异所指示的多个位置。同时,我们需要将该差值减去偏差指数(并检查下溢或次正常情况)并重新归一化数字(左移尾数,并递减指数,直到尾数中的第一个转到隐藏比特位置)

我假设模数的偏差指数低于要操作的数字的指数,就像在另一种情况下,掩码是全1,并且数字不受掩码的影响。