PDA

View Full Version : Help converting this math formula into code, please.



kryton9
02-12-2010, 13:12
I have no idea how to take a math formula like this and make it workable code. I sure can use some help.

I am interested in:
Two-dimensional Gaussian function. There is a screenshot that shows the shape.

http://en.wikipedia.org/wiki/Gaussian_function

Thanks for any help!

Michael Hartlef
02-12-2010, 16:59
http://www.site.uottawa.ca/~edubois/courses/CEG4311/plotting_2D.pdf

kryton9
02-12-2010, 18:20
Thanks Mike, but that doesn't help me understand how to figure out such conversions. The wikipedia page also had some code written in a language named Octave, but I couldn't match how they came up with that code looking at the mathematic formula.

Charles Pegge
02-12-2010, 19:10
Hi Kent,

I would deconstruct the first formula in the Wiki then apply it to x and z dimensions to get the y.



'Gaussian hump

dim as double a,b,c,e,g,hx,x,y,z

e=2.718281828 'Euler's number e

'In a single dimension x

assuming centre b is 0

g=-0.5*(x*x)/(c*c)
hx=a*e^g

'in x and z dimensions (using pythagoras to get distance from centre)

g=-0.5*(x*x+z*z)/(c*c)
y=a*e^g



You can then iterate on x and z to get the corresponding y.

Charles

PS correction to my previous by applying pythagoras.

kryton9
02-12-2010, 23:21
Thanks Charles will try it out now and study. I will post when I get it to do what I want, thanks again!

danbaron
03-12-2010, 03:13
Here is a thinBasic script which "plots" (numerically) to the console, the two dimensional Gaussian Function, i.e., the equation at the top of the following web page, ==>

http://en.wikipedia.org/wiki/Gaussian_function

It makes the plot twice, for two values of the parameter, "c", which determines the sharpness of the curve's "peak".

:p
Dan


'-----------------------------------------------------------------------------------------------
' Empty console script created on 12-02-2010 15:37:59 by (ThinAIR)
'-----------------------------------------------------------------------------------------------
' FILE = "Gauss2D.tbasic"
'-----------------------------------------------------------------------------------------------

Uses "console"

' "c" should not be set equal to 0.

' "a" is the "y" value when "x" equals "b".
' "a" is the maximum (or minimum for negative values of "a") "y" value.
' If "a" is negative, then the curve will be upside down (the "peak" will point down).

' "b" is the "x" value at the center of the symmetric curve.
' "b" is also the "x" value corresponding to the maximum "y" value.

' "c" determines the width of the peak.
' The curve will look exactly the same for "c" equals "z", or for "c" equals negative "z" (because the formula only uses "c" squared).
' For instance, if "c" equals 1, the curve will look narrower, than if "c" equals 10.

'-----------------------------------------------------------------------------------------------

Function TBMain()
Local i As Ext
Local x, y, w, a, b, c As Ext
Local s As String

'------------------------------------------------------------

' Let the "plot" extend from negative "w" to positive "w".
' Arbitrarily, set "w" equal to 10.
w = 10

' Put the center of the curve at "x" equals 0.
b = 0

' Make the maximum value of the curve equal to 1000.
a = 1000

' First, try "c" equals 1.
c = 1

'------------------------------------------------------------

For x = -w To w Step w / 50
y = Gauss2D(x, a, b, c)
s = Format$(x, "+00.000;-00.000")
Console_WriteLine(s, " ", y)
Next

'------------------------------------------------------------
Console_WriteLine("")
'------------------------------------------------------------

' Now, try "c" equals 10.
c = 10

For x = -w To w Step w / 50
y = Gauss2D(x, a, b, c)
s = Format$(x, "+00.000;-00.000")
Console_WriteLine(s, " ", y)
Next
'------------------------------------------------------------

WaitKey
End Function

'-----------------------------------------------------------------------------------------------

Function Gauss2D(x As Ext, a As Ext , b As Ext, c As Ext) As Ext
Return a * Exp(-((x - b)^2/2/c^2))
End Function

'-----------------------------------------------------------------------------------------------

kryton9
03-12-2010, 04:48
Thanks Dan, came back to check the forums after banging my head against the wall and still not getting it. Now with this new Energy Code Bar you gave me, feel energized and will see if I can do what I wanted. Thanks again!

kryton9
03-12-2010, 06:47
Thanks for the help Dan, Charles and Mike.

I see now that this method will not help me meet my goal, but it is nice to have forums like this and a language like thinBasic to test out things like this quickly!


'
' The most basic skeleton for TBGL
' started on 12-02-2010
' Thanks Dan and Charles for code and help!

Uses "TBGL"

Function TBMain()

Local i As Ext
Local x, y, w, a, b, c As Ext
'Local s As String

'------------------------------------------------------------

' Let the "plot" extend from negative "w" to positive "w".
' Arbitrarily, set "w" equal to 10.
w = 20

' Put the center of the curve at "x" equals 0.
b = 0

' Make the maximum value of the curve equal to 1000.
a = 15

' First, try "c" equals 1.
c = 5

'------------------------------------------------------------

Local hWnd As DWord
Local FrameRate As Double

' -- Create and show window
hWnd = TBGL_CreateWindowEx("Roswell Effect: Failed Attempt One - press ESC to quit", 640, 480, 32, %TBGL_WS_WINDOWED Or %TBGL_WS_CLOSEBOX)
TBGL_ShowWindow


%Gauss2D = 1
TBGL_NewList %Gauss2D
TBGL_PushMatrix
'draw red lines first
TBGL_Color(255, 0, 0)
TBGL_BeginPoly %GL_LINES
For x = -w To w Step w / 50
y = Gauss2D(x, a, b, c)
TBGL_Vertex x,y
Next
TBGL_EndPoly

'draw yellow points
TBGL_PointSize 1
TBGL_Color(255, 255, 0)
TBGL_BeginPoly %GL_POINTS
For x = -w To w Step w / 50
y = Gauss2D(x, a, b, c)
TBGL_Vertex x,y
Next
TBGL_EndPoly
TBGL_PopMatrix
TBGL_EndList

' -- Resets status of all keys
TBGL_ResetKeyState()

' -- Main loop
While TBGL_IsWindow(hWnd)
FrameRate = TBGL_GetFrameRate

TBGL_ClearFrame
TBGL_Camera(0, 30, 30, 0, 0, 0)

For x = 1 To 15
TBGL_Rotate 24, 0,1,0
TBGL_CallList %Gauss2D
Next

TBGL_DrawFrame

' -- ESCAPE key to exit application
If TBGL_GetWindowKeyState(hWnd, %VK_ESCAPE) Then Exit While

Wend

TBGL_DestroyWindow
End Function


'-----------------------------------------------------------------------------------------------

Function Gauss2D(x As Ext, a As Ext , b As Ext, c As Ext) As Ext
Return a * Exp(-((x - b)^2/2/c^2))
End Function

'-----------------------------------------------------------------------------------------------

Charles Pegge
03-12-2010, 07:26
I dropped the Gauss form into the Oxygen OpengGL 4 port demo:
You can try other functions by editing the procedure below:

Charles




'====================================================================
' DrawShape() - Draw a solid shape (use a display list for the model)
'====================================================================

sub DrawShape

static as single e,g,x,y,z,nx,ny,nz,g
static as long shape_list, i,j,k


if not shape_list
'
'Record the plot list
'--------------------
'
shape_list = glGenLists 1
glNewList( shape_list, GL_COMPILE_AND_EXECUTE )
'
'Draw the shape
'
e=2.718281828 'Euler's number
z=2.5
for i = 1 to 20
'
x=-2.5
glBegin GL_QUAD_STRIP
'
for j = 1 to 20
'
'
'PLOT
'----
'
g=-.5*(x*x+Z*Z)
y=-1+2*pow(e,g)
'y = 2.5-sqr(x*x+Z*Z)
nx = x
ny = y
nz = z
'
glNormal3f nx, ny, nz
glVertex3f x, y, z
'
z-=.25
'
g=-.5*(x*x+Z*Z)
y=-1+2*pow(e,g)
'y = 2.5-sqr(x*x+Z*Z)
nx = x
ny = y
nz = z
'
glNormal3f nx, ny, nz
glVertex3f x, y, z
'
z+=.25
x+=.25
'
next
'
glEnd()
z-=.25
'
next
'
glEndList()
'
else
'
'Playback displaylist
'
glCallList( shape_list )
end if
end sub

danbaron
03-12-2010, 07:41
Previously, I gave you f(x).

If, you want f(x, y), then, there are two equations at the bottom of the web page ( http://en.wikipedia.org/wiki/Gaussian_function ) (the plot labeled, "Gaussian curve with a 2-dimensional domain").

I'm guessing that you don't need the second equation. It is for rotating the elliptical plot in the x-y plane.

Here is the function for the first equation (in which the major axis of the ellipse is parallel to one global axis (x or y), and the minor axis of the ellipse is parallel to the other global axis.)


Function Gauss3D(x As Ext, y As Ext, a As Ext, x0 As Ext, xs As Ext, y0 As Ext, ys As Ext) As Ext
' The "s" in xs means "sigma". That is the Greek character that appears in one of the denominators of the equation's exponent.
' The lowercase Greek character sigma, looks like "o".
' The "s" in ys means "sigma". That is the Greek character that appears in the other denominator of the equation's exponent.

' You would call this function like this.
' z = Gauss3D(x, y, a, x0, xs, y0, ys)

' (x, y) is the point in the x-y plane at which you want the value of "z".
' "a" is the maximum (or minimum for negative "a") value of the function.
' (xo, yo) is the point at the function's center (at z = a = f(x0, y0, a, x0, xs, y0, ys)).

' The value of xs determines the spread of the function in the x direction.
' The value of ys determines the spread of the function in the y direction.

' For a circular plot, set ys = xs.


Return a * Exp(-((x - x0)^2/2/xs^2 + (y - y0)^2/2/ys^2))
End Function

The Octave code is for using the second equation. That is used if you want to rotate the plot in the x-y plane (like the three plots shown at the bottom of the web page). If you need that, then, say so. It is not very hard.

The Octave code uses sigma_x = 1, and, sigma_y = 2. That means that before the plot is rotated, the ellipse appears like it extends twice as far in the y direction, as in the x direction. The Octave code rotates the ellipse by pi (180 degrees).

In the Octave code, theta is the angle (the uppercase Greek character theta, looks like a zero with a horizontal line through the middle) of rotation in the x-y plane. When theta equals 0, the plot has not been rotated. When theta equals pi/2, the plot has been rotated 90 degrees. When theta equals pi, the plot has been rotated 180 degrees.

(I guess I misunderstood what you meant by "two-dimensional", in your original post. A plot, f(x), is two dimensional in the sense that it is a plane curve, so it has two dimensions (unless it is a line). But, it is one dimensional in the sense that it has one independent variable, x. Likewise, a plot, f(x, y), is three dimensional in the sense that it is a curved surface, so it has three dimensions (unless it is a plane). But, it is two dimensional in the sense that it has two independent variables, x and y.)

(The "failed" plot you made, looks nice, like Christmas lights.)

kryton9
03-12-2010, 09:38
@Charles looks super, will download and play with it for sure!

@DanThanks for the further clarifications Dan. I decided to turn the old program into a tinker program for doing plots like this to experiment easily.

Arrow keys move the camera left/right up/down
keys a z move the camera in and out

Left mouse down and move mouse rotates the object

Right mouse click resets the objects rotation

This is using the older Dan's Gauss code and multiplied with sin(x), wild

kryton9
03-12-2010, 09:46
Dan, I forgot to point out that I really like the way you explain the variables and symbols. I spent a couple of hours today looking up symbols on wikipedia and found out that different fields use the same or very similar symbol in their equations which adds to the confusion to non math types like me.

So thanks for taking the time and explaining it so well. Maybe you should make a website and start teaching math for guys like me. Almost all the sites I find for the explanation of math is explained for people who already are mathematicians and not for self taught perpetual students!

kryton9
03-12-2010, 10:33
Last one for the night. I wanted to make a version with animation.
I have other ones to check out in the code.
Don't forget keys a and z move the camera in and out
arrow keys move the camera leftRight upDown

Left mouse button down move mouse rotates the plot

danbaron
04-12-2010, 07:43
It works pretty good.

I turned the lights off in the room and it looks spooky.

I guess it would be better if you could automatically make it the size of the full screen. Then, I wouldn't be able to see the lighter desktop at the boundaries. But, maybe that's hard to do. But it would be nice - it would be really creepy in a dark room.

The mouse and all of the keys work as advertised.

I move the camera out, and it reminds me of a galaxy floating in space, and doing something weird.

Basically, it reminds me of some strange thing in the middle of interstellar space, maybe a cosmic intelligence. I can imagine them looking out the window of the Enterprise, seeing it, and saying, "What the f**k is that?!".

The bubbles floating through the middle look good, and the mouse rotation works good and fast.

:p
Dan

kryton9
04-12-2010, 09:28
Dan you have a great imagination as the Roswell Effect was going to be this image that was burned into my mind after watching the tv show Roswell.

Basically in the show, 3 kids crash at Roswell and are aliens. They end up being adopted into 2 families. There are 2 boys and 1 girl. The one boy and girl are adopted by a nice family and the second boy by an abusive man who just wanted the money he would get from the government to take care of him.

Anyways as teenagers it is the story of their life. The one alien boy falls in love with an Earthling girl. In the first season something strange happens. When they have any physical contact they start seeing images of the other's youth.

To make this long story short, they touch and the earth girl sees a movie of the alien boys trip to earth and they go flying by what to me looked like a red galaxy with a massive black hole. The video was just a couple of seconds and moving quickly, but that was such a cool breathe taking image that I wanted to try to recreate it.

So eventually I will get there. I could cheat and do it by painting in photoshop and making a video, but I want to make it via code.

If you want to see the episode it is on Hulu for free:
http://www.hulu.com/watch/4563/roswell-sexual-healing?c=Science-Fiction#s-p2-n1-so-i0

If you want to just see the cool flyby, move to the 7 minute mark into the episode.

As I wrote this I tried to take a screenshot and it worked. But it looks cool when the camera whizzes by it.

danbaron
04-12-2010, 10:13
As of now, my Internet connection is too slow to watch any video Kent. Maybe someday. I like the screen shot though.

Wouldn't it be cool if the alien teenagers pulled off their human skins, and underneath they looked like octopuses? Then they grasped the humans with their tentacles, and ate them with their beaks? (Just kidding.)

I agree that code is harder, but, most likely better. Your background is black, it doesn't show any stars. If I remember correctly, that is realistic for deep space. The stars we see in the sky are all from our own galaxy. If we were inside a spaceship in deep space, far from any galaxies, and we looked out the window with our naked eyes, I think all we would see would be black. And on a long trip, that would be creepy, lonely, and claustrophobic, wouldn't it? Additionally, there is no sound in space. So, if you (or I) turned off the spaceship's lights and went outside, it would be perfectly black, and perfectly silent (you could probably hear yourself breathing). (Make sure you are attached by a rope to the ship, otherwise, the joke won't be very funny.) I think that if you started drifting away from the ship, even very very slowly, and you were not attached, and you had no means of propulsion, then, you would have a big problem - unless there was someone still in the ship who would maneuver it to pick you up. But, in the general case, if someone threw you out of a ship into deep space, then, for you, it would not be a good day (and the same for me if someone threw me out).

:p

kryton9
04-12-2010, 23:29
Dan, space is incredible. When I was studying and using Dark Basic Professional a few years back, I made a full scale 3d model of our Solar System. I put all the planets in a line out from the Sun so I could find them as I flew.

Anyways I very quickly found out it was very boring flying out from the Sun to the planets as the distances where so great and the size of the planets so small that they were hard to find when flying even when going straight.

As you said out in between galaxies it would be very bad. Unless the galaxies themselves appeared as stars? I don't know.

Remember that one space horror movie, I forgot the name now, but the catch phrase for it was, "in space, no one can hear you scream". Without sound spaceships flying don't have the same effect in my test movies I have made. I guess we got conditioned to hearing cool special effects when seeing spaceships fly in movies. It does make it more fun and better in my opinion to not go for true reality in games or movies.

danbaron
05-12-2010, 09:44
I absolutely remember, "In space no one can hear you scream.". Last night, in my post, I thought about using it.

-----------------------------------------

I thought about making a scale model of the solar system in grade school. For instance, you could use a basketball for the Sun. The diameter of a basketball is 9.39 inches. The diameter of the Sun is approximately 800,000 miles. So, my scale would be 1 inch equals approximately 85197 miles.

Earth is 93,000,000 miles from the Sun, so, I would have to put it

93000000 / 85197 = 1092 inches from the basketball, which is approximately 91 feet away.

The diameter of the Earth is about 8,000 miles, so I would need a sphere

8000 / 85197 = 0.09 inches in diameter, to represent the Earth (probably smaller than a BB).

Soon, you realize, that if you make a scale model of the solar system, you will mostly have empty space.

-----------------------------------------

I do believe that close galaxies appear as stars, our closest neighbor Andromeda, for instance.

Like I said in the other thread, the Milky Way is 100,000 light years across, and then the next galaxy, Andromeda, is 2.5 million light years away. I think that if you were in a spaceship halfway between the Milky Way and Andromeda, and you looked out the window, it would be like standing in a coal mine (maybe, you could see two "stars", the Milky Way, and Andromeda).

There are places on Earth that seem almost uninhabitable to us. But, I think they are like Paris compared to deep space. There, there's no food, water, air, materials. The pressure is zero, and the temperature is approximately -455 degrees Fahrenheit.

I agree that it makes for a better movie to show space less inhospitable and bleak than it actually is. If you showed it objectively, it would just be black nothingness (between galaxies).

Maybe there is intragalactic travel either here or elsewhere (but, I don't see how). But, I doubt if there is intergalactic travel.

In my opinion the voids between galaxies are like the ultimate "no man's lands".

I don't know if any aliens from other stars in the Milky Way have ever visited Earth. But, if there was some way to determine it, I would bet a lot of money that none from another galaxy have ever visited Earth (and, I wouldn't be surprised, if none ever do - to me, 2.5 million light years, is a long way). Maybe it would be possible to send machines, but how would they survive for millions of years? They would have to repair themselves, like cells in a body.

Remember, according to Einstein, attaining the speed of light is impossible - forever.

Concerning for instance, wormholes, I think you would need the energy of an entire galaxy, to me, it's dreaming. And even if you had one, how would you determine where you were going to be when you exited it?

:p

-----------------------------------------

Now I see that I made a big mistake.

According to this link, our nearest neighboring galaxy, is only 42,000 light years away, the Canus Major Dwarf Galaxy. That's a lot closer than 2,500,000, yes? Sorry. It says it has an ellipsoid shape, and one billion stars. (To me, 42,000 light years is still a long way.) Andromeda, is only the nearest, spiral galaxy. And, Andromeda is the farthest object visible with the naked eye.

http://en.wikipedia.org/wiki/Canis_Major_Dwarf_Galaxy

-----------------------------------------

Now I see that there are a lot of galaxies closer than Andromeda.

http://en.wikipedia.org/wiki/List_of_nearest_galaxies

(Sometimes, it's better not to post anything.)

-----------------------------------------

Here is some interesting stuff about the galaxies near ours.

http://uk.answers.yahoo.com/question/index?qid=20060926051142AAN9Rd6

jack
06-12-2010, 00:57
Dan, I think aliens have long ago discovered how to travel by "time displacement" it's not the primitive propulsion system that we have.

kryton9
06-12-2010, 01:41
The distances for sure our mind numbing.

As elegant as the universe is, I am sure there is a way to travel between galaxies. Maybe in a different way of travel than what we can think of today.

danbaron
06-12-2010, 02:08
It could be that there are ways of traveling between galaxies, that we can never think of. It could be that we are not smart enough. It seems to me that humans assume they are smart enough to solve every problem. I don't think that's necessarily true. My dogs can't solve a lot of problems that I can solve. We could be like my dogs compared to some species in the universe. My experience is that, that possibility never seems to occur to most people.

The Canus Major Dwarf Galaxy, our closest known neighbor was only discovered in 2003. It is relatively very close to us. The Milky Way is 100,000 light years in diameter. The center of Canus Major Dwarf, is only 42,000 light years from the center of the Milky Way. So, Canus Major Dwarf must reside either "above" or "below" (how do you determine what constitutes "above", and, what constitutes "below"?) the plane of the Milky Way's spiral. Otherwise, it would intersect the Milky Way, since the radius of the Milky Way is 50,000 light years. It seems strange that astronomers have previously found much more distant objects, but, until 2003, missed Canus Major, which is relatively "on top" of us.

Another thing which is astounding to me about our universe, is that it extends in every direction. I always think of traveling through space, in the plane of our solar system. But, you can also travel in two directions perpendicular to the plane of our solar system. When I think about that, it sort of astonishes me.

We, in the 21st century are in awe of the size of the universe. I think the current estimate is that the Milky Way contains 100 billion stars. And, there are approximately 7 billion people on Earth. So, each person could "own" approximately 14 stars, just in our galaxy. We're rich! I bet if in, say, the 17th century, people learned what we know about how big the universe is, they would faint. And, maybe we would too, if we knew what people will know 400 years from now.

What are we doing here? I really don't understand what's going on.

jack
06-12-2010, 04:00
it seems we are doom to re-eterate to our mistakers; not long ago I dreamed about a circle and a spaceship on how to return to our humble beginnings.