From e154a158a9f77ef686f99b6aa873980d0fca0650 Mon Sep 17 00:00:00 2001 From: James Roseborough Date: Sat, 22 Sep 2007 05:25:02 +0000 Subject: [PATCH] Add ipow, to compute power for integers. --- src/main/java/lua/value/LDouble.java | 25 ++++++++++++++++++++++--- src/main/java/lua/value/LInteger.java | 10 +++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/main/java/lua/value/LDouble.java b/src/main/java/lua/value/LDouble.java index 78909248..2613f8f7 100644 --- a/src/main/java/lua/value/LDouble.java +++ b/src/main/java/lua/value/LDouble.java @@ -52,12 +52,31 @@ public class LDouble extends LNumber { case Lua.OP_MUL: return new LDouble( lhs * rhs ); case Lua.OP_DIV: return new LDouble( lhs / rhs ); case Lua.OP_MOD: return new LDouble( lhs - Math.floor(lhs/rhs) * rhs ); - -// case Lua.OP_POW: return new LDouble( Math.pow(lhs, rhs) ); + // case Lua.OP_POW: return new LDouble( dpow(lhs, rhs) ); } return luaUnsupportedOperation(); } - + + /* + public static double dpow(double a, double b) { + if ( b < 0 ) + return 1 / dpow( a, -b ); + int p = 1; + int whole = (int) b; + for ( double v=a; whole > 0; whole>>=1, v=v*v ) + if ( (whole & 1) != 0 ) + p *= v; + int frac = (int) (0x10000 * b); + for ( ; (frac&0xffff)!=0; frac<<=1 ) { + a = Math.sqrt(a); + if ( (frac & 0x8000) != 0 ) + p *= a; + } + return p; + } + */ + + public int luaAsInt() { return (int) m_value; } diff --git a/src/main/java/lua/value/LInteger.java b/src/main/java/lua/value/LInteger.java index 16c4a5ad..eb866e9d 100644 --- a/src/main/java/lua/value/LInteger.java +++ b/src/main/java/lua/value/LInteger.java @@ -43,11 +43,19 @@ public class LInteger extends LNumber { case Lua.OP_MUL: return new LInteger( m_value * rhs ); case Lua.OP_DIV: return new LInteger( m_value / rhs ); case Lua.OP_MOD: return new LInteger( m_value - ((int) Math.floor(m_value/(double)rhs)) * rhs ); -// case Lua.OP_POW: return new LInteger( (int) Math.pow(m_value, rhs) ); + case Lua.OP_POW: return new LInteger( ipow(m_value, rhs) ); } return luaUnsupportedOperation(); } + private static int ipow(int v, int rhs) { + int p = 1; + for ( ; rhs > 0; rhs>>=1, v=v*v ) + if ( (rhs & 1) != 0 ) + p *= v; + return p; + } + // binary operations on mixed integer, double public LValue luaBinOpDouble(int opcode, double rhs) { return LDouble.luaBinOpDoubleDouble(opcode, (double) m_value, rhs );