Strange Exponent Issue

Basic and Machine Language

Moderator: Moderators

Post Reply
Nibby99vic
Vic 20 Newbie
Posts: 3
Joined: Fri May 31, 2013 5:28 am

Strange Exponent Issue

Post by Nibby99vic »

Just starting to get back into BASIC on the vic after 25+ years or so and I was playing around with the exponent function (x^2 type thing) and was checking that verses x*x for speed and for some reason using the x^2 was giving strange results with floating point outputs that didn't make sense (7^2 should be 49 not 49.0000001 shouldn't it?). Also the P*P is much faster that using the exponent..

See screenshot
Image
User avatar
Kweepa
Vic 20 Scientist
Posts: 1314
Joined: Fri Jan 04, 2008 5:11 pm
Location: Austin, Texas
Occupation: Game maker

Post by Kweepa »

That's because x*x does a multiply, but x^2 uses a general exponential function with exponent 2.0. VIC BASIC doesn't do any clever optimization tricks.
Dusty
Vic 20 Amateur
Posts: 51
Joined: Sun Feb 13, 2011 7:43 am

Post by Dusty »

OT: The whole thing should go into a FOR..NEXT loop (should be a bit faster than, too - and saves memory):

Code: Select all

20 PRINT "NUMBER","SQUARE"
30 FOR P=1 TO 8
40 PRINT P,P^2
50 NEXT
User avatar
Mike
Herr VC
Posts: 4831
Joined: Wed Dec 01, 2004 1:57 pm
Location: Munich, Germany
Occupation: electrical engineer

Post by Mike »

Hi, Nibby99,

this thread should shed some more light on this. ;)

In short, exponentiation is a much more complex operation than multiplication. For this reason, it is also prone to rounding errors, that's why you get a non-integer result with 7^2.
Kweepa wrote:VIC BASIC doesn't do any clever optimization tricks.
It's still an interpreter, the routines are tuned for space and an acceptable speed in the general case. They could have implemented SQR() with Heron's Algorithm though, instead of doing X^(1/2). :?

That being said, the arithmetic routines themselves are not too shabby speed-wise, when they are called directly from machine language. It might be an interesting exercise to come up with faster versions of the basic arithmetic (addition, subtraction, multiplication and division) without sacrifying accuracy.
RJBowman
Vic 20 Enthusiast
Posts: 198
Joined: Tue Oct 25, 2011 7:50 pm

Re: Strange Exponent Issue

Post by RJBowman »

Nibby99vic wrote:7^2 should be 49 not 49.0000001 shouldn't it?]
It is a little known fact that the first Pentiums were prototyped using a modified VIC-20.
FD22
Vic 20 Hobbyist
Posts: 148
Joined: Mon Feb 15, 2010 12:31 pm

Re: Strange Exponent Issue

Post by FD22 »

RJBowman wrote:
Nibby99vic wrote:7^2 should be 49 not 49.0000001 shouldn't it?]
It is a little known fact that the first Pentiums were prototyped using a modified VIC-20.
Indeed. Also, you may not have realised that the 'microcode' that drives all modern processors is actually 6502 assembly.
Post Reply