Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
strange behaviour of raise to power
#1
In this code:

DIM x1, x2 AS float
x1 = -3
x2 = x1^2
PRINT x2


if x1 = 3 (or any positive number) the correct result (9) is printed.
If x1 = -3  I get no result in the output (nothing is printed on the screen) and no message is shown.
I've tried to define x1 and x2 as integer, with the same problem.
I'm using 1.17.3 version with ZX Basic Studio, but I also tried with Visual Studio Code and Fuse (same result).
I'm doing something wrong or it's a bug?
Thanks
Reply
#2
Sort of.
ZX Basic uses the ROM FP-Calc. Unfortunately, (-3)^2 (or any other negative integer) gives Invalid Argument.
Indeed, you should get this error when returning to BASIC.
This is a limitation of the ROM FP-Calc which uses Logarithms to compute the power of a number. Hence powers of negative numbers cannot be computed. However, you can do x * x in this case.
I'm looking for an alternative to this, but for floats it's not easy: x^y for x < 0 (negative numbers) is tricky if y is float. For example (-3)^0.5 is the same as SQR(-3) which is imaginary (and will return also Invalid Argument).
Maybe there is an algorithm using the ROM FP to compute this?
---
Boriel
Reply
#3
Thank you for your reply.
a^n with n integer and a real could be compute creating a function based on multiplication (sort of power(a,n)). The case with n float is very difficult. Perhaps some solution based on Taylor series expansion? It's just an idea, I don't know if it is possible...
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)