Any VB programmers out there: using Double-type variables and Pi

Started by TerranRich, Tue 17/05/2005 21:24:24

Previous topic - Next topic

TerranRich

Hey all,

If you use Visual Basic, then I need your help, citizen! :=

I'm programming a calculator-like program in VB. Whenever I use the trigonometric functions, like Sine and Cosine, for certain values I get answers very close to zero but not quite.

For example, when finding the Tangent of Pi/2, the answer is undefined (or infinitely positive/negative), but instead I get -286411217403671 for an answer. Similarly, when I find the Sine of Pi (which is supposed to be 0), I get 3.23108510433268E-15 (scientific notation for an extremely small number).

I am pretty sure it might have something to do with the fact that I am using Doubles everywhere in the code, but I did this so that the answers would be as accurate as possible. Of course, now they're a bit TOO accurate. On the other hand, I think it might very well have something to do with my declaration of Pi:

Code: ags
Const Pi = Atn(1) * 4


This is a known representation of Pi, and it's an accurate approximation. Could that be the problem in my code?

Any help would be greatly appreciated.
Status: Trying to come up with some ideas...

Colxfile

If you rearrange the equation Pi = Arctan(1) *4, you get tan(Pi/4)=1. (Which, obviously, is correct) So I doubt there's anything wrong with your approximation.

Hmm, I just thought that this was a problem with floating point numbers for all programming languages. Theres a similar problem in C as I recall.

Basically, the minute differences are caused by the conversion from base 2 to base 10 being not-quite-perfect. Or something like that.

I think... But that doesn't explain how the windows calculator gets it right.



One thing you could try is stealing 100 decimal places of pi from a website and somehow outwitting the compiler so that you can use that as your Pie instead. But I'm not sure that Visual Basic will be happy with that.

Alternatively, you could hard code in routines that stop the calculator from giving these wrong results. So if the commands entered amount to tan(Mississippi Mud Pie/two) than instead of working the answer out, an error message comes up. Likewise when a sine / cosine function that SHOULD return 1 / 0 is called for, the answer is simply 1 / 0. Or, for the  trigonometric results that are known, introduce some kind of rounding up/down function that'll make the answer 1 or nought or 0.5 (Sine(Pi/6)=0.5, does that one work for your calculator?)
Always carry a UV marker pen with you. When you go to a shop or a friend's house, if you see something you like, put your name and postcode on it. If it gets stolen and subsequently recovered, the police will get in touch with you so that they can 'return' it.

stuh505

why don't you just round to a certain number of decimel places?  you're never going to have perfect accuracy

SMF spam blocked by CleanTalk