Tag: 乘法

java中的浮点乘法

可能重复: 如何在Java中将数字舍入到n个小数位 当在java中乘以两个数字时,会发生以下情况: double a = 9.495 * 100; 预期结果: a = 949.5; 但获得的结果是: a = 949.4999999999999 当我尝试以小数点后两位舍入数字9.495时,结果是9.49而不是9.50 任何想法如何解决这个问题?

快速方形双倍

我正在寻找最快的双倍方式( double d )。 到目前为止,我提出了两种方法: 1. d*d 2. Math.pow(d, 2) 为了测试性能,我设置了三个测试用例,每个测试用例使用相同的种子为三种情况生成随机数,然后计算循环中的平方数1000000次。 在第一个测试用例中,使用random.nextDouble()生成数字,在第二种情况下使用random.nextDouble()*Double.MAX_VALUE ,在第三种情况下使用random.nextDouble()*Double.MAX_VALUE random.nextDouble()*Double.MIN_VALUE 。 几次运行的结果(近似结果,总是有一些变化,使用java 1.8运行,在Mac OSX Mavericks上为java 1.6编译) Approach | Case 1 | Case 2 | Case 3 ———•——–•——–•——- 1 | ~2.16s | ~2.16s | ~2.16s 2 | ~9s | ~30s | ~60s 结论似乎是方法1更快,但Math.pow似乎表现得有些奇怪。 所以我有两个问题: 1为什么Math.pow如此缓慢,为什么它会严重处理> 1 ,更糟糕的是< -1数? 2有没有办法提高性能超过我建议的方法1? 我在想的是: long l […]

Java中的Fork连接矩阵乘法

我正在对Java 7中的fork / join框架进行一些性能研究。为了改进测试结果,我想在测试期间使用不同的递归算法。 其中一个是乘法矩阵。 我从Doug Lea的网站()下载了以下示例: public class MatrixMultiply { static final int DEFAULT_GRANULARITY = 16; /** The quadrant size at which to stop recursing down * and instead directly multiply the matrices. * Must be a power of two. Minimum value is 2. **/ static int granularity = DEFAULT_GRANULARITY; public static void main(String[] […]

在arrays上绘制笛卡尔积

我有兴趣在n个arrays上执行笛卡尔积。 如果我提前知道数组的数量,我可以编写代码。 例如,给定2个数组: int[] a = new int[]{1,2,3}; int[] b = new int[]{1,2,3}; for(int i=0; i<=a.length; i++){ for(int j=0; j<=b.length; j++){ System.out.println(a[i]*b[j]); } } 问题是在运行时,我不知道数组的数量。 我可能有2个arrays,或者我可能有100个arrays。 有没有办法可以做到这一点? 谢谢!

BigInteger大部分时间都是优化乘法

嗨我想以最及时优化的方式乘以2大整数。 我目前正在使用karatsuba算法。 任何人都可以建议更优化的方式或算法来做到这一点。 谢谢 public static BigInteger karatsuba(BigInteger x, BigInteger y) { // cutoff to brute force int N = Math.max(x.bitLength(), y.bitLength()); System.out.println(N); if (N <= 2000) return x.multiply(y); // optimize this parameter // number of bits divided by 2, rounded up N = (N / 2) + (N % 2); // x = a […]

java中双精度乘法的准确性?

对于java中的double值,乘法运算符的保证精度是多少? 例如,2.2 * 100是220.00000000000003,但220是双数。 220.00000000000003是220后的下一个双倍。

按位乘法并在Java中添加

我有使用乘法和加法的方法,但我只是无法理解它们。 它们都来自外部网站而不是我自己的网站: public static void bitwiseMultiply(int n1, int n2) { int a = n1, b = n2, result=0; while (b != 0) // Iterate the loop till b==0 { if ((b & 01) != 0) // Logical ANDing of the value of b with 01 { result = result + a; // Update the result […]