1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Two Factor Authentication is now available on BeyondUnreal Forums. To configure it, visit your Profile and look for the "Two Step Verification" option on the left side. We can send codes via email (may be slower) or you can set up any TOTP Authenticator app on your phone (Authy, Google Authenticator, etc) to deliver codes. It is highly recommended that you configure this to keep your account safe.

Useful math functions here!

Discussion in 'Programming' started by usaar33, Feb 5, 2002.

?

Did you find this info useful?

  1. Yes

    12 vote(s)
    80.0%
  2. No

    3 vote(s)
    20.0%
  1. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    I always wanted these functions, so when I was bored today, I quickly wrote them.

    Algebraic functions:
    A^B
    Code:
    native(170) static final operator(12) float ** ( float A, float B );
    
    I'm only listing this here, as few know of it. A**B means A^B. You can use this to do cube roots (num**(1/3)), etc.
    Note that for e^x, you should use Exp(x)

    My own:
    Code:
    static final function float Logarithm (float a, optional float Base){
      if (Base==0)
        Base=10;
      return Loge(a)/Loge(base);
    }
    
    UT lacks a log function, but did have an ln (Loge). I exploited this fact to write this function. First paremeter is the number to take the log of, base is the log base (default 10, as a base of 0 is impossible).
    Reasoning behind code:
    Code:
    log (Base) a =Res
    Base^Res = a
    ln (Base^Res) = ln a
    Res*ln(Base) = ln a
    Res=(ln a)/(ln base)
    

    Trigonometic:

    Note that all trig functions shown here (and in unrealscript) are calculated with radians. Some constants to convert between them and other units:
    Code:
    Const RadianToDegree = 57.2957795131;
    Const DegreeToRadian = 0.01745329252;
    Const RadianToURot = 10430.3783505;
    Const URotToRadian = 0.000095873799;
    
    URot is the unreal rotation unit, where a full rotation is 2^16 units (rotators use this unit).

    Unrealscript has a sin, cos, and tan function, but unfortunately, the only inverse function is atan...

    Inverse Sin function (pass the sin of an angle, and it returns the angle):
    Like atan, it will return an angle between -pi and pi.
    Code:
    static final function float ASin  ( float A ){
      if (A>1||A<-1) //outside domain!
        return 0;
      if (A==1)  //div by 0 checks
        return Pi/2.0;
      if (A==-1)
        return Pi/-2.0;
      return ATan(A/Sqrt(1-Square(A)));
    }
    
    Reasoning:
    I rely on the pythagorean identity ( sin^2 x + cos ^2 x = 1), as well as the fact that tan x is defined as sin x / cos x. The reasoning behind the formula should then be obvious. Also note that the domain is -1<=A<=1, due to sin's nature.

    Inverse Cos function (pass the cos of an angle, and it returns the angle). This is very useful to get angles between vectors (Acos (v1 dot v2)):

    Code:
    static final function float ACos  ( float A ){
      if (A>1||A<-1) //outside domain!
        return 0;
      if (A==0) //div by 0 check
        return (Pi/2.0);
      A=ATan(Sqrt(1.0-Square(A))/A);
      if (A<0)
        A+=Pi;
      Return A;
    }
    
    Similar expaination to asin. Note that pi is added if A<0 to shift from 3rd quad to 1st.


    More exact inverts.
    The following functions allow you to pass ratios with two numbers. For every angle on a circle, with the exception of two per trig function, there is another angle that has the same sin, cos, or tan. Using ratios allows the exact angle to be returned.

    ArcTangent2. Pass the adjacent triangle leg as X and the opposite leg as Y (or X compoent, Y compont of a triangle inscribed in a unit circle).:
    Note that if Y and X are 0, it will return 0, although in reality there is no answer (no line = no angle).
    Code:
    final static function float ATan2(float Y,float X)
    {
     local float tempang;
     
     if(X==0) { //div by 0 checks.
      if(Y<0)
       return -pi/2.0;
      else if(Y>0)
       return pi/2.0;
      else
       return 0; //technically impossible (nothing exists)
     }
     tempang=ATan(Y/X);
    
     if (X<0)
      tempang+=pi;  //1st/3th quad
    
     //normalize (from -pi to pi)
     if(tempang>pi) 
      tempang-=pi*2.0;
     
     if(tempang<-pi)
      tempang+=pi*2.0;
       
     return tempang;
    }
    
    ArcSin2: a more precise asin. Y=opposite leg, R=radius/hypotenuse. Of course if R is 0, no line exists, so it will return 0. Note that this assumes you put my asin code in your script.
    Code:
    final static function float ASin2(float Y,float Rad)
    {
     local float tempang;
     
     if(Rad==0)
       return 0; //technically impossible (no hypotenuse = nothing)
     tempang=ASin(Y/Rad);
    
     if (Rad<0)
      tempang=pi-tempang;  //lower quads
    
     return tempang;
    }
    
    ACos2: a more precise acos. X=adjecent leg, R=opposite. Other rules are similar to ASin2:

    Code:
    final static function float ACos2(float X,float Rad)
    {
     local float tempang;
     
     if(Rad==0)
       return 0; //no possible angle
     tempang=ACos(X/Rad);
    
     if (X<0)
      tempang*=-1;  //left quads
    
     return tempang;
    }
    
    Well, inform me if this is useful or not :) I hope I was of service (of cource, you could have easily written these functions yourself, but whatever :p)
     
  2. arcanex

    arcanex teh grinning totem

    Joined:
    Sep 28, 2001
    Messages:
    123
    Likes Received:
    0
    Too bad I have no idea what all the sin and cos stuff do. Maybe somebody should try to explain all of that stuff in a tutorial for the less than mathematically knowledgeable.
     
  3. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    I assume that the reader has taken a basic Geometry 2 course (2nd semester sophmore year math equivilent in American High School). Honestly, I would assume just to code unreal mods, you would need trig knowledge (2 years more advanced).

    I guess you are in Middle School or something? Just wait a year or two :p

    Anyway, quck trig lesson.
    See the circle below?

    The SIN function is defined as the ratio of the Y (green) coordinate (opposite line) with respect to the (purple) radius (hypotenuse of the right triangle) of whatever theta is. (the angle)... i.e. SIN theta = Y/radius

    The COS function is Adjacent/X (Brown).

    TAN is Opposite/Adjacent.

    The inverse functions take in the ratio and return the angle.

    Now go read a good trig/geometry book :p
     
  4. Guy ON Drugs

    Guy ON Drugs He who knows but doesn't know he knows

    Joined:
    Jan 26, 2002
    Messages:
    24
    Likes Received:
    0
    i'm 15 and in the 10th a got a ways to go before i start understanding all that crap. thanks alot though. i know now that i'm FOR SURE going to college, cause i wanna get paid($chaaaching$) programing for some company/business
     
  5. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    1) Stay off drugs. They hamper your learning abilities :p
    2) Your school must suck. I'm in Cali, where schools are really supposed to suck, but if you are in geometry and have not yet learned sin and cos, your school uber-sux :p
     
  6. navboy

    navboy New Member

    Joined:
    Jan 5, 2001
    Messages:
    340
    Likes Received:
    0
    it seems like crap when you don't know it, but as soon as you find a real use for it it's great. If you want to get paid money to program the sooner you learn it the better. Regardless of where your school curriculum is at, you could learn the basics of it in two or three days with a good book or a good website, and then you'd have the rudiments of a great tool under your belt

    Even tho it's not strictly programming, it's crucial for problem solving, and i'd never hire any programmer that didn't know it, and i'd certainly prefer a programmer who took some pleasure in it ... ;)
     
  7. arcanex

    arcanex teh grinning totem

    Joined:
    Sep 28, 2001
    Messages:
    123
    Likes Received:
    0
    Still unclear, maybe I should check near the back of my book (I'm in 2nd sem geometry right now, but we're going pretty slow....our quiz tomorrow is on the PYTHAGOREAN THEOREM....CA schools suck) 'cause I think I saw some sin and cos stuff there.

    But still, how the heck are you suppose to use this in uscript? I can think of some application in the physics stuff maybe, but that should've been hardcoded anyway, right? Or maybe vectors/rotators....which I'm also having problems figuring out....
     
  8. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    Heh, what part of Cali?
    The coolest weapons rely on physics, especially vectors. If I didn't know this stuff, many of my mods could have never been made :p
    Don't even bother with vectors and rotators unless you know what sin and cos are :p
     
  9. SoSilencer

    SoSilencer Harry Goz (1932 - 2003)

    Joined:
    Nov 27, 2000
    Messages:
    834
    Likes Received:
    0
    I've been doing complex vector stuff for over 6 months and I have no clue what any of those things are ;)

    Of course in reality I probably do use them, I just don't know that I'm using them or what they are called.
     
  10. Sonja

    Sonja New Member

    Joined:
    Nov 25, 2001
    Messages:
    24
    Likes Received:
    0
    just to recap:
    In every triangle where one angle is 90 degrees,
    the side opposite the 90 degrees angle is the hypotenuse,
    For the other two angles remember,

    soh cah toa.

    where s = sin of any of the two angles
    c = cos of any of the two angles
    t = tan of any of the two angles
    o = length of the side opposite the angle
    a = length of the side adjecent the angle
    h = hypotenuse

    Example:
    soh --> sin(angle) = o/h
     
  11. Guy ON Drugs

    Guy ON Drugs He who knows but doesn't know he knows

    Joined:
    Jan 26, 2002
    Messages:
    24
    Likes Received:
    0
    no joke my school is poor most people in my school are drug dealers but hey im trying =)
     
  12. KillerMonk

    KillerMonk UScript and VC++ Master Mind

    Joined:
    Jan 9, 2002
    Messages:
    48
    Likes Received:
    0
    Does that mean that my school is good? I'm in 10th grade and am in PreCalculus, and ComputerScience AP. Oh, Guy ON Drugs, I would suggest taking as many ComputerScience classes as you can, and try to get into an AP class for it. Also, take a CNA ( Networking ) class. That will really help you.
     
  13. tarquin

    tarquin design is flawed

    Joined:
    Oct 11, 2000
    Messages:
    3,945
    Likes Received:
    0
    Handy stuff. I always wondered why UScript doesn't have all 3 inverse trigs, I found it quite inconvenient. My Acos function looks pretty much the same as yours. :)
    I did trig at 13. :) Though I think the UK maths curriculum has slipped back a bit since then.

    Here are ones I've used:
    Code:
    const UUCircle 		= 65536.0f ;
    const ZeroVect 		= vect(0,0,0);
    
    (For some reason vect(0,0,0) produces an error when used within a function call.)

    divides is an operator that returns true if A is a divisor of B. eg ( 3 divides 5 ) = false, and ( 3 divides 6 ) = true.
    Code:
    static final operator(24) bool divides ( float A , float B )
    {
    	if( int( B / A ) == B / A )
    		return true ;
    }
    
    Sgn(x) returns +1, 0 or -1 depending on the sign of x.

    Code:
    function float Sgn( float theValue )
    {
    if( theValue == 0 )
    	return 0;
    return theValue / Abs(theValue);
    }
    
    mod is a replacement for the Uscript % operator doesn't behave how I expect it to for negative numbers. Eg: -8 % 10 = -8, where I would expect it to be 2.

    Code:
    static final operator(18) float mod  ( float A, float B )
    {
    	if( A % B >= 0 )
    		return A % B ;
    	else
    		return ( A % B ) + B ;
    }
    
    I'll make a page in the Wiki for these :)
     
  14. Eater1

    Eater1 Coder

    Joined:
    Oct 22, 2000
    Messages:
    176
    Likes Received:
    0
    In some schools, CS classes really suck, so make sure you know what you're getting into so you don't waste time. As for those functions usaar: I never really needed any of them (except asin and acos... needed those for making a radar a long, long time ago)... I suppose they might come in handy if you're going to be making something and trying to be REALLY realistic physics-wise, but for a game like UT, people care more about the gameplay than the physics, so while time spent coding proper physics would make your game more realistic, time spent coding cool special effects would make your game far more interesting for gamers (especially those that play UT). But yeah, a knowledge of geometry and trig is a very useful thing to have for programming, especially for games.

    Eater.
     
  15. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    ya.. I'm still working on a car with wheels. (/me worries about rolling resistance, friction, air resistance, and actually treats rotations with torques on all 3 axis).

    Trig at 13? When did you take calculus?
    /me had trig at 14 and calc at 15.
     
  16. tarquin

    tarquin design is flawed

    Joined:
    Oct 11, 2000
    Messages:
    3,945
    Likes Received:
    0
    I'm pretty sure I did sin/cos/tan in 3rd year of high school. Just basic definitions & then interminable problems about ladders leaning against walls (who are these irresponsible people who leave their ladders lying around, I ask you! ch! :p )
    I didn't do Calculus until 1st year of A level.

    Apparently, GCSE maths doesn't cover algebra any more. :eek: so A level Chemistry students have to tackle equations by learning silly diagrams & mnemonics, because they don't know how to re-arrange terms. scary...
     
  17. Raeled

    Raeled Feuer Frei!

    Joined:
    Jul 1, 2001
    Messages:
    161
    Likes Received:
    0
    when me learned it, sin.coz and tan where just some 'magic' numbers :)
    where they come from?, from ya'r calculator!, hmm :)

    4 year i learned where they acctually came from.

    used them a lot between that time, and didn't even know what it acctually was :)
     
  18. mr.s-d

    mr.s-d CHiMERiC Moderator

    Joined:
    Aug 30, 2001
    Messages:
    65
    Likes Received:
    0
    Hmm, trig in year 9? I swear we never touched it until KS4, but then again where I went to school we used the god awful smile system...
     
  19. Papapishu

    Papapishu 我是康

    Joined:
    Jun 18, 2001
    Messages:
    2,043
    Likes Received:
    0
    I just love trigonometry. :D
    That's the only math I can bear at all...

    About the operator, doesn't UScript already have the ** operator?
    If you check the tech page you'll find the section right under "Language Functionality" a list of operators, and last in the list I find:
    ** float Exponentiation
    :confused:

    I learned a great deal of trigonometry by plotting graphic with it in BASIC once upon a time...
     
  20. usaar33

    usaar33 Un1337

    Joined:
    Mar 25, 2000
    Messages:
    808
    Likes Received:
    0
    pap, I know, but many have missed it.

    Tarq, thanks for those further functions. Anyone can feel free to add to this post with more functions.

    A level? KS4? What the heck are you guys talking about? :p
    /me=American
     

Share This Page