I know this is a retarded question, but I need some help with a method I need to write. The method parameters are a double and an int (a and b, respectively)
I need to write a for loop in the method that raises a (the double) to the power of b (the int)
How the fuck do I do this?? Normally this wouldn't be a problem, but I'm burnt out from finals
In computation it's a good choice because it will usually result in a correct ultimate result rather than an aborted one. Even though its undefined, its limit is 1 and that is usually all your program needs.
pubic static doubles powpowpow(double a, int b) {
if(b<0)
return 1/powpowpow(a,-b);
else if(!b)
return 1;
else {
// this is left as an exercise for the reader
}
}
Name:
Anonymous2011-12-10 19:36
>>11 else if (!b)
that type of shit doesn't work in java, you need to implicitly compare to 0
>>11
You don't need a special case: let powpow a b =
let rec powpow a b c = match b < 1 with
if b < 1 then c (* the only terminal call *)
else powpow a (b - 1) (c *. a) in
let negpow a b = 1.0 /. (powpow a (-b) 1.0) in
if b < 0 then negpow a b
else powpow a b 1.0;;
Name:
Anonymous2011-12-10 22:38
If you don't know how to do this already, you probably shouldn't be programming... Just think about what power means...
if (b == 0) { return 1; }
else if (b == 1) { return a; }
else {
double c = a;
for (/*you're writing this one faggot*/) {
c = c * a;
}
return c;
By the way, I don't know dick about Java, so I can't tell if the syntax is correct.
Oops, mispaste: let powpow a b =
let rec powpow a b c =
if b < 1 then c
else powpow a (b - 1) (c *. a) in
let negpow a b = 1.0 /. (powpow a (-b) 1.0) in
if b < 0 then negpow a b
else powpow a b 1.0;;
>>16
Nice negatives powers. let powpow a b =
let rec powpow a b c =
if b < 1 then c
else powpow a (b - 1) (c *. a) in
powpow a b 1.0;;
>>18
Right. There are other expressly indeterminate limits, which is a big part of why it's left undefined in general. (Which is certainly "more correct" but usually less useful.)
>>23
For the first example, there's no limit coming from negative infinity (0n is always undefined if n < 0). It didn't really matter in the second one, but it looked good.
private PowerFactory()
{
pows = new HashMap<Double, HashMap<Integer, Double>>();
}
public double power(int a, double b)
{
double ans = 0;
HashMap<Integer, Double> ins
if (pows.containsKey(b))
{
ins = pows.get(b);
if (ins.containsKey(a))
ans = ins.get(a);
else
{
ans = raise(a, b);
ins.put(a, ans);
}
}
else
{
ins = new HashMap<Integer, Double>();
ans = raise(a, b);
ins.put(a, ans);
pows.put(b, ins);
}
return ans;
}
private static raise(int a, double b)
{
double res = b;
for (int i = 1; i < a; i++)
res *= b;
return res;
}
}