Search Results

Search found 255 results on 11 pages for 'pow'.

Page 4/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Which is faster in Python: x**.5 or math.sqrt(x)?

    - by Casey
    I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? UPDATE This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido van Rossum an email cause I really wanted to know the differences in these methods. My email: There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better? His response: pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...

    Read the article

  • C++: how to truncate the double in efficient way?

    - by Arman
    Hello, I would like to truncate the float to 4 digits. Are there some efficient way to do that? My current solution is: double roundDBL(double d,unsigned int p=4) { unsigned int fac=pow(10,p); double facinv=1.0/static_cast<double>(fac); double x=static_cast<unsigned int>(x*fac)/facinv; return x; } but using pow and delete seems to me not so efficient. kind regards Arman.

    Read the article

  • Problem in finalizing the link list in C#

    - by Yasin
    My code was almost finished that a maddening bug came up! when i nullify the last node to finalize the link list , it actually dumps all the links and make the first node link Null ! when i trace it , its working totally fine creating the list in the loop but after the loop is done that happens and it destroys the rest of the link by doing so, and i don't understand why something so obvious is becoming problematic! (last line) struct poly { public int coef; public int pow; public poly* link;} ; poly* start ; poly* start2; poly* p; poly* second; poly* result; poly* ptr; poly* start3; poly* q; poly* q2; private void button1_Click(object sender, EventArgs e) { string holder = ""; IntPtr newP = Marshal.AllocHGlobal(sizeof(poly)); q = (poly*)newP.ToPointer(); start = q; int i = 0; while (this.textBox1.Text[i] != ',') { holder += this.textBox1.Text[i]; i++; } q->coef = int.Parse(holder); i++; holder = ""; while (this.textBox1.Text[i] != ';') { holder += this.textBox1.Text[i]; i++; } q->pow = int.Parse(holder); holder = ""; p = start; //creation of the first node finished! i++; for (; i < this.textBox1.Text.Length; i++) { newP = Marshal.AllocHGlobal(sizeof(poly)); poly* test = (poly*)newP.ToPointer(); while (this.textBox1.Text[i] != ',') { holder += this.textBox1.Text[i]; i++; } test->coef = int.Parse(holder); holder = ""; i++; while (this.textBox1.Text[i] != ';' && i < this.textBox1.Text.Length - 1) { holder += this.textBox1.Text[i]; if (i < this.textBox1.Text.Length - 1) i++; } test->pow = int.Parse(holder); holder = ""; p->link = test; //the addresses are correct and the list is complete } p->link = null; //only the first node exists now with a null link! }

    Read the article

  • PHP Strange error "0:". Possible Object syntax problem?

    - by Michael Stone
    I'm trying to transfer a site from one hosting company to another. I was using 000webhost until the client had hosting and a domain. Now that the client has their domain and hosting, using FatCow.com, I can not for the life of me, debug my PHP code. I'm not getting any errors. I have a successful DB connection. If you procedurally display data, it works, but when I try to use my original objects, something is breaking and just returns "0:". I have all errors on. On old server where the site worked: PHP Version 5.2.11 MySQL Version: 5.0.81 On new server where I get the "0:": PHP Version 5.2.12 MySQL Version 5.0.32 I've setup a test page to test just the output of the variables with the DB connection. Below is my code: <?php error_reporting(E_ALL); ini_set('display_errors', '1'); try { $link = mysql_connect('connectionstring', 'username', 'password'); if (!$link) { die('Could not connect: ' . mysql_error()); } else{ $db = mysql_select_db('a8210422_lit'); } if($db){ include_once('admin/classes/clsPOW.php'); include_once('admin/classes/clsProviders.php'); $pow = new POW(); $prov = new Providers(); $new = $pow->getNew(); $newAr = $new->val(); $get = $prov->getAll($newAr['providerId']); $getAr = $get->val(); $img = $getAr['image']; $name = $getAr['provider']; $desc = $getAr['description']; $zip = $getAr['zip']; $web = $getAr['link']; if($zip==0){ $zip = "Unavailable"; } print $img; print $name; print $desc; print $zip; print $web; } else{ print 'fail!'; } } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>

    Read the article

  • Python beginner, strange output problem

    - by Protean
    I'm having a weird problem with the following piece of code. from math import sqrt def Permute(array): result1 = [] result2 = [] if len(array) <= 1: return array for subarray in Permute(array[1:]): for i in range(len(array)): temp1 = subarray[:i]+array[0]+subarray[i:] temp2 = [0] for num in range(len(array)-1): temp2[0] += (sqrt(pow((temp1[num+1][1][0]-temp1[num][1][0]),2) + pow((temp1[num+1][1][1]-temp1[num][1][1]),2))) result1.append(temp1+temp2) return result1 a = [['A',[50,1]]] b = [['B',[1,1]]] c = [['C',[100,1]]] array = [a,b,c] result1 = Permute(array) for i in range(len(result1)): print (result1[i]) print (len(result1)) What it does is find all the permutations of the points abc and then returns them along with the sum of the distances between each ordered point. It does this; however, it also seems to report a strange additional value, 99. I figure that the 99 is coming from the computation of the distance between point a and c but I don't understand why it is appearing in the final output as it does.

    Read the article

  • python geometry help

    - by Enriquev
    Hello, I have the following problem, I am trying to find the following distances (F1 and F2): This is what I have as of now: def FindArrow(self, X1, Y1, X2, Y2, X3, Y3): self.X1 = float(X1) self.Y1 = float(Y1) self.X2 = float(X2) self.Y2 = float(Y2) self.X3 = float(X3) self.Y3 = float(Y3) #center coords of the circle self.Xc = None self.Yc = None #radius self.R = None #F1 and F2 self.FAB = None self.FBC = None #check if the coordinates are collinear invalide = self.X1 * (self.Y2 - self.Y3) + self.X2 * (self.Y3 - self.Y1) + self.X3 * (self.Y1 - self.Y2) if (invalide == 0): return #get the coords of the circle's center s = (0.5 * ((self.X2 - self.X3)*(self.X1 - self.X3) - (self.Y2 - self.Y3) * (self.Y3 - self.Y1))) / invalide self.Xc = 0.5 * (self.X1 + self.X2) + s * (self.Y2 - self.Y1) self.Yc = 0.5 * (self.Y1 + self.Y2) + s * (self.X1 - self.X2) #get the radius self.R = math.sqrt(math.pow(self.Xc - self.X1, 2) + math.pow(self.Yc - self.Y1, 2)) Until here everything seems to work, now what would be the next steps to get F1 and F2 ?

    Read the article

  • Why is FLD1 loading NaN instead?

    - by Bernd Jendrissek
    I have a one-liner C function that is just return value * pow(1.+rate, -delay); - it discounts a future value to a present value. The interesting part of the disassembly is 0x080555b9 : neg %eax 0x080555bb : push %eax 0x080555bc : fildl (%esp) 0x080555bf : lea 0x4(%esp),%esp 0x080555c3 : fldl 0xfffffff0(%ebp) 0x080555c6 : fld1 0x080555c8 : faddp %st,%st(1) 0x080555ca : fxch %st(1) 0x080555cc : fstpl 0x8(%esp) 0x080555d0 : fstpl (%esp) 0x080555d3 : call 0x8051ce0 0x080555d8 : fmull 0xfffffff8(%ebp) While single-stepping through this function, gdb says (rate is 0.02, delay is 2; you can see them on the stack): (gdb) si 0x080555c6 30 return value * pow(1.+rate, -delay); (gdb) info float R7: Valid 0x4004a6c28f5c28f5c000 +41.68999999999999773 R6: Valid 0x4004e15c28f5c28f6000 +56.34000000000000341 R5: Valid 0x4004dceb851eb851e800 +55.22999999999999687 R4: Valid 0xc0008000000000000000 -2 =R3: Valid 0x3ff9a3d70a3d70a3d800 +0.02000000000000000042 R2: Valid 0x4004ff147ae147ae1800 +63.77000000000000313 R1: Valid 0x4004e17ae147ae147800 +56.36999999999999744 R0: Valid 0x4004efb851eb851eb800 +59.92999999999999972 Status Word: 0x1861 IE PE SF TOP: 3 Control Word: 0x037f IM DM ZM OM UM PM PC: Extended Precision (64-bits) RC: Round to nearest Tag Word: 0x0000 Instruction Pointer: 0x73:0x080555c3 Operand Pointer: 0x7b:0xbff41d78 Opcode: 0xdd45 And after the fld1: (gdb) si 0x080555c8 30 return value * pow(1.+rate, -delay); (gdb) info float R7: Valid 0x4004a6c28f5c28f5c000 +41.68999999999999773 R6: Valid 0x4004e15c28f5c28f6000 +56.34000000000000341 R5: Valid 0x4004dceb851eb851e800 +55.22999999999999687 R4: Valid 0xc0008000000000000000 -2 R3: Valid 0x3ff9a3d70a3d70a3d800 +0.02000000000000000042 =R2: Special 0xffffc000000000000000 Real Indefinite (QNaN) R1: Valid 0x4004e17ae147ae147800 +56.36999999999999744 R0: Valid 0x4004efb851eb851eb800 +59.92999999999999972 Status Word: 0x1261 IE PE SF C1 TOP: 2 Control Word: 0x037f IM DM ZM OM UM PM PC: Extended Precision (64-bits) RC: Round to nearest Tag Word: 0x0020 Instruction Pointer: 0x73:0x080555c6 Operand Pointer: 0x7b:0xbff41d78 Opcode: 0xd9e8 After this, everything goes to hell. Things get grossly over or undervalued, so even if there were no other bugs in my freeciv AI attempt, it would choose all the wrong strategies. Like sending the whole army to the arctic. (Sigh, if only I were getting that far.) I must be missing something obvious, or getting blinded by something, because I can't believe that fld1 should ever possibly fail. Even less that it should fail only after a handful of passes through this function. On earlier passes the FPU correctly loads 1 into ST(0). The bytes at 0x080555c6 definitely encode fld1 - checked with x/... on the running process. What gives?

    Read the article

  • error in encryption program

    - by Raja
    #include<iostream> #include<math.h> #include<string> using namespace std; int gcd(int n,int m) { if(m<=n && n%m ==0) return m; if(n<m) return gcd(m,n); else return gcd(m,n%m); } int REncryptText(char m) { int p = 11, q = 3; int e = 3; int n = p * q; int phi = (p - 1) * (q - 1); int check1 = gcd(e, p - 1); int check2 = gcd(e, q - 1); int check3 = gcd(e, phi); // // Compute d such that ed = 1 (mod phi) //i.e. compute d = e-1 mod phi = 3-1 mod 20 //i.e. find a value for d such that phi divides (ed-1) //i.e. find d such that 20 divides 3d-1. //Simple testing (d = 1, 2, ...) gives d = 7 // double d = Math.Pow(e, -1) % phi; int d = 7; // public key = (n,e) // (33,3) //private key = (n,d) //(33 ,7) double g = pow(m,e); int ciphertext = g %n; // Now say we want to encrypt the message m = 7, c = me mod n = 73 mod 33 = 343 mod 33 = 13. Hence the ciphertext c = 13. //double decrypt = Math.Pow(ciphertext, d) % n; return ciphertext; } int main() { char plaintext[80],str[80]; cout<<" enter the text you want to encrpt"; cin.get(plaintext,79); int l =strlen(plaintext); for ( int i =0 ; i<l ; i++) { char s = plaintext[i]; str[i]=REncryptText(s); } for ( int i =0 ; i<l ; i++) { cout<<"the encryption of string"<<endl; cout<<str[i]; } return 0; }

    Read the article

  • PHP - Why does my computation produce a different result when I assign it to a variable?

    - by David
    I want to round a number to a specific number of significant digits - basically I want the following function: round(12345.67, 2) -> 12000 round(8888, 3) -> 8890 I have the following, but there's a strange problem. function round_to_sf($number, $sf) { $mostsigplace = floor(log10(abs($number)))+1; $num = $number / pow(10, ($mostsigplace-$sf)); echo ($number / pow(10, ($mostsigplace-$sf))).' '.$num.'<BR>'; } round_to_sf(41918.522, 1); Produces the following output: 4.1918522 -0 How can the result of a computation be different when it's assigned to a variable?

    Read the article

  • return type while using GMP.h header file

    - by Raveesh_Kumar
    While i m using gmp.h header file. i need a fuction which takes inputs of type mpz_t and return mpz_t type too. I m very beginner of using gmp.h So, Here is snaps follows of my approached code.... mpz_t sum_upto(mpz_t max) { mpz_t sum; mpz_init(sum); mpz_init(result); for(int i=0;i<=max-1;i++) mpz_add_ui(sum,sum,pow(2,i)); return sum; } but it will show error 1 ." pow has been not used in this scope.",although i have added math.h in very beginnig of the file. 2 . sum_upto declared as function returning an array... do tell as soon as possible. i have to complete my very big project....

    Read the article

  • Python to C# Conversion of RGBA values not working

    - by clangers
    I'm currently converting some python code to C#, and I'm having an issue with the RGBA C# libraries # Original Python Code: d = math.sqrt( (x - size/2.0)**2 + (y - size/2.0)**2 ) rgbVal = int(200*d/md + 50) rgba = (0,0,0, 255 - rgbVal) img.putpixel((x,y), rgba) // My C# Code double d = Math.Sqrt(Math.Pow((x - DotSize / 2.0), 2) + Math.Pow((y - DotSize / 2.0), 2)); int rgbVal = (int) (200 * d / md + 50); Color color = Color.FromArgb(255 - rgbVal, 0, 0, 0); // ** ERROR ** img.SetPixel(x,y, color); At both instances of the code d is equal to 106 and md is equal to 53. However the resulting rgbVal value is 450. This would obviously mean that 255 - 450 is -195, which causes an error to be thrown as each individual value must be between 0 and 255. Anyone have any idea how I can fix this. Please note that the data is the same when running both the python and C# versions.

    Read the article

  • C Different answers for a variable when running 'Debug' and 'Start without debug'

    - by Craz
    I keep getting this weird output from my code everytime I use the 'start without degugging' (ctrl-F5) as opposed to normal 'debug' (F5). When I try to find the following value of norm_differnece in debug (pressing F5) mode, it gives me the correct answer for norm_difference normdifference = 1.000000 but in 'start without debugging' (pressing ctrl-f5) the wrong output normdifference = 1456816083547664100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 The following is a segment of code which is gives the output Note: X[] = is a array of stored DOUBLE values for(i=0;i<n;i++){ sum_difference += (pow((X[i*n]-X[i]),2)); } norm_difference = sqrt(norm_difference); for(i=0;i<n;i++){ sum_norm_1 += pow(X[i],2); } norm_1 = sqrt(norm_1); //Take square root of the sum of squares for the row printf("normdifference = %f \n norm_1 = %f \n",norm_difference,norm_1);

    Read the article

  • Proper Translation of equation to C#

    - by Shykin
    I am trying to replicate this equation: Slope(b) = (NSXY - (SX)(SY)) / (NSX2 - (SX)2) in C# but I'm getting the following issue: If I make the average of X = 1 + 2 + 3 + 4 + 5 and the average Y = 5 + 4 + 3 + 2 + 1 it gives me a positive slope even though it is clearly counting down. If I place the same numbers into this calculator: http://www.easycalculation.com/statistics/regression.php It gives me a negative slope in the linked calculator with the same data. I'm trying to narrow down the reasons so is the following a proper translation from equation to C# code: Slope(b) = (NSXY - (SX)(SY)) / (NSX2 - (SX)2) to Slope (m) = ((x * avgX * avgY) - (avgX * avgY)) / ((x * Math.Pow(avgX, 2)) - Math.Pow(avgX, 2));

    Read the article

  • How to speed up this simple mysql query?

    - by Jim Thio
    The query is simple: SELECT TB.ID, TB.Latitude, TB.Longitude, 111151.29341326*SQRT(pow(-6.185-TB.Latitude,2)+pow(106.773-TB.Longitude,2)*cos(-6.185*0.017453292519943)*cos(TB.Latitude*0.017453292519943)) AS Distance FROM `tablebusiness` AS TB WHERE -6.2767668133836 < TB.Latitude AND TB.Latitude < -6.0932331866164 AND FoursquarePeopleCount >5 AND 106.68123318662 < TB.Longitude AND TB.Longitude <106.86476681338 ORDER BY Distance See, we just look at all business within a rectangle. 1.6 million rows. Within that small rectangle there are only 67,565 businesses. The structure of the table is 1 ID varchar(250) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 2 Email varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 3 InBuildingAddress varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 4 Price int(10) Yes NULL Change Change Drop Drop More Show more actions 5 Street varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 6 Title varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 7 Website varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 8 Zip varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 9 Rating Star double Yes NULL Change Change Drop Drop More Show more actions 10 Rating Weight double Yes NULL Change Change Drop Drop More Show more actions 11 Latitude double Yes NULL Change Change Drop Drop More Show more actions 12 Longitude double Yes NULL Change Change Drop Drop More Show more actions 13 Building varchar(200) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 14 City varchar(100) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 15 OpeningHour varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 16 TimeStamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP Change Change Drop Drop More Show more actions 17 CountViews int(11) Yes NULL Change Change Drop Drop More Show more actions The indexes are: Edit Edit Drop Drop PRIMARY BTREE Yes No ID 1965990 A Edit Edit Drop Drop City BTREE No No City 131066 A Edit Edit Drop Drop Building BTREE No No Building 21 A YES Edit Edit Drop Drop OpeningHour BTREE No No OpeningHour (255) 21 A YES Edit Edit Drop Drop Email BTREE No No Email (255) 21 A YES Edit Edit Drop Drop InBuildingAddress BTREE No No InBuildingAddress (255) 21 A YES Edit Edit Drop Drop Price BTREE No No Price 21 A YES Edit Edit Drop Drop Street BTREE No No Street (255) 982995 A YES Edit Edit Drop Drop Title BTREE No No Title (255) 1965990 A YES Edit Edit Drop Drop Website BTREE No No Website (255) 491497 A YES Edit Edit Drop Drop Zip BTREE No No Zip (255) 178726 A YES Edit Edit Drop Drop Rating Star BTREE No No Rating Star 21 A YES Edit Edit Drop Drop Rating Weight BTREE No No Rating Weight 21 A YES Edit Edit Drop Drop Latitude BTREE No No Latitude 1965990 A YES Edit Edit Drop Drop Longitude BTREE No No Longitude 1965990 A YES The query took forever. I think there has to be something wrong there. Showing rows 0 - 29 ( 67,565 total, Query took 12.4767 sec)

    Read the article

  • How to implement a simple bullet trajectory

    - by AirieFenix
    I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have). I have a top-down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing). a: vector of the position of the gun/player. b: vector of the mouse position (cross-hair). w: the vector of the bullet's trajectory. So, w=b-a. And the position of the bullet = [x=x0+speed*time*normalized w.x , y=y0+speed*time * normalized w.y]. I have the constructor: public Shot(int shipX, int shipY, int mouseX, int mouseY) { //I get mouse with Gdx.input.getX()/getY() ... this.shotTime = TimeUtils.millis(); this.posX = shipX; this.posY = shipY; //I used aVector = aVector.nor() here before but for some reason didn't work float tmp = (float) (Math.pow(mouseX-shipX, 2) + Math.pow(mouseY-shipY, 2)); tmp = (float) Math.sqrt(Math.abs(tmp)); this.vecX = (mouseX-shipX)/tmp; this.vecY = (mouseY-shipY)/tmp; } And here I update the position and draw the shot: public void drawShot(SpriteBatch batch) { this.lifeTime = TimeUtils.millis() - this.shotTime; //position = positionBefore + v*t this.posX = this.posX + this.vecX*this.lifeTime*speed*Gdx.graphics.getDeltaTime(); this.posY = this.posY + this.vecY*this.lifeTime*speed*Gdx.graphics.getDeltaTime(); ... } Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it); if it's a calculation problem, a code problem or both. Also, is it possible that Gdx.input.getX() gives me non-precise position? Because when I draw the cross-hair it also draws off the cursor position. Sorry for the long post and sorry if it's a very basic question. Thanks!

    Read the article

  • determine collision angle on a rotating body

    - by jorb
    update: new diagram and updated description I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function html canvas coordinates and the Box2d rotation information. I know I have to account for this somehow... SS below questions: Does Box2D provide these angles more directly in the collision information? Am I even on the right track? If so, any hints? I have the following javascript so far: Ship.prototype.onCollide = function (other_ent,cx,cy) { var pos = this.body.GetPosition(); //collision position relative to body var d_cx = pos.x - cx; var d_cy = pos.y - cy; //length of initial vector var len = Math.sqrt(Math.pow(pos.x -cx,2) + Math.pow(pos.y-cy,2)); //body angle - can over rotate hence mod 2*Pi var ang = this.body.GetAngle() % (Math.PI * 2); //vector representing body's angle - same magnitude as the first var b_vx = len * Math.cos(ang); var b_vy = len * Math.sin(ang); //dot product of the two vectors var dot_prod = d_cx * b_vx + d_cy * b_vy; //new calculation of difference in angle - NOT WORKING! var d_ang = Math.acos(dot_prod); var side; if (Math.abs(d_ang) < Math.PI/2 ) side = "front"; else side = "back"; console.log("length",len); console.log("pos:",pos.x,pos.y); console.log("offs:",d_cx,d_cy); console.log("body vec",b_vx,b_vy); console.log("body angle:",ang); console.log("dot product",dot_prod); console.log("result:",d_ang); console.log("side",side); console.log("------------------------"); }

    Read the article

  • Bump mapping Problem GLSL

    - by jmfel1926
    I am having a slight problem with my Bump Mapping project. Although everything works OK (at least from what I know) there is a slight mistake somewhere and I get incorrect shading on the brick wall when the light goes to the one side or the other as seen in the picture below: The light is on the right side so the shading on the wall should be the other way. I have provided the shaders to help find the issue (I do not have much experience with shaders). Shaders: varying vec3 viewVec; varying vec3 position; varying vec3 lightvec; attribute vec3 tangent; attribute vec3 binormal; uniform vec3 lightpos; uniform mat4 cameraMat; void main() { gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = ftransform(); position = vec3(gl_ModelViewMatrix * gl_Vertex); lightvec = vec3(cameraMat * vec4(lightpos,1.0)) - position ; vec3 eyeVec = vec3(gl_ModelViewMatrix * gl_Vertex); viewVec = normalize(-eyeVec); } uniform sampler2D colormap; uniform sampler2D normalmap; varying vec3 viewVec; varying vec3 position; varying vec3 lightvec; vec3 vv; uniform float diffuset; uniform float specularterm; uniform float ambientterm; void main() { vv=viewVec; vec3 normals = normalize(texture2D(normalmap,gl_TexCoord[0].st).rgb * 2.0 - 1.0); normals.y = -normals.y; //normals = (normals * gl_NormalMatrix).xyz ; vec3 distance = lightvec; float dist_number =length(distance); float final_dist_number = 2.0/pow(dist_number,diffuset); vec3 light_dir=normalize(lightvec); vec3 Halfvector = normalize(light_dir+vv); float angle=max(dot(Halfvector,normals),0.0); angle= pow(angle,specularterm); vec3 specular=vec3(angle,angle,angle); float diffuseterm=max(dot(light_dir,normals),0.0); vec3 diffuse = diffuseterm * texture2D(colormap,gl_TexCoord[0].st).rgb; vec3 ambient = ambientterm *texture2D(colormap,gl_TexCoord[0].st).rgb; vec3 diffusefinal = diffuse * final_dist_number; vec3 finalcolor=diffusefinal+specular+ambient; gl_FragColor = vec4(finalcolor, 1.0); }

    Read the article

  • Best way to implement a simple bullet trajectory

    - by AirieFenix
    I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have). I have a top-down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing). a: vector of the position of the gun/player. b: vector of the mouse position (cross-hair). w: the vector of the bullet's trajectory. So, w=b-a. And the position of the bullet = [x=x0+speed*time*normalized w.x , y=y0+speed*time * normalized w.y]. I have the constructor: public Shot(int shipX, int shipY, int mouseX, int mouseY) { //I get mouse with Gdx.input.getX()/getY() ... this.shotTime = TimeUtils.millis(); this.posX = shipX; this.posY = shipY; //I used aVector = aVector.nor() here before but for some reason didn't work float tmp = (float) (Math.pow(mouseX-shipX, 2) + Math.pow(mouseY-shipY, 2)); tmp = (float) Math.sqrt(Math.abs(tmp)); this.vecX = (mouseX-shipX)/tmp; this.vecY = (mouseY-shipY)/tmp; } And here I update the position and draw the shot: public void drawShot(SpriteBatch batch) { this.lifeTime = TimeUtils.millis() - this.shotTime; //position = positionBefore + v*t this.posX = this.posX + this.vecX*this.lifeTime*speed*Gdx.graphics.getDeltaTime(); this.posY = this.posY + this.vecY*this.lifeTime*speed*Gdx.graphics.getDeltaTime(); ... } Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it); if it's a calculation problem, a code problem or both. Also, is it possible that Gdx.input.getX() gives me non-precise position? Because when I draw the cross-hair it also draws off the cursor position. Sorry for the long post and sorry if it's a very basic question. Thanks!

    Read the article

  • Atmospheric scattering OpenGL 3.3

    - by user1419305
    Im currently trying to convert a shader by Sean O'Neil to version 330 so i can try it out in a application im writing. Im having some issues with deprecated functions, so i replaced them, but im almost completely new to glsl, so i probably did a mistake somewhere. Original shaders can be found here: http://www.gamedev.net/topic/592043-solved-trying-to-use-atmospheric-scattering-oneill-2004-but-get-black-sphere/ My horrible attempt at converting them: Vertex Shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; //layout(location = 1) in vec2 vertexUV; layout(location = 2) in vec3 vertexNormal_modelspace; uniform vec3 v3CameraPos; uniform vec3 v3LightPos; uniform vec3 v3InvWavelength; uniform float fCameraHeight; uniform float fCameraHeight2; uniform float fOuterRadius; uniform float fOuterRadius2; uniform float fInnerRadius; uniform float fInnerRadius2; uniform float fKrESun; uniform float fKmESun; uniform float fKr4PI; uniform float fKm4PI; uniform float fScale; uniform float fScaleDepth; uniform float fScaleOverScaleDepth; // passing in matrixes for transformations uniform mat4 MVP; uniform mat4 V; uniform mat4 M; const int nSamples = 4; const float fSamples = 4.0; out vec3 v3Direction; out vec4 gg_FrontColor; out vec4 gg_FrontSecondaryColor; float scale(float fCos) { float x = 1.0 - fCos; return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); } void main(void) { vec3 v3Pos = vertexPosition_modelspace; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; vec3 v3Start = v3CameraPos; float fHeight = length(v3Start); float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fCameraHeight)); float fStartAngle = dot(v3Ray, v3Start) / fHeight; float fStartOffset = fDepth*scale(fStartAngle); float fSampleLength = fFar / fSamples; float fScaledLength = fSampleLength * fScale; vec3 v3SampleRay = v3Ray * fSampleLength; vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5; vec3 v3FrontColor = vec3(0.0, 0.0, 0.0); for(int i=0; i<nSamples; i++) { float fHeight = length(v3SamplePoint); float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight)); float fLightAngle = dot(v3LightPos, v3SamplePoint) / fHeight; float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight; float fScatter = (fStartOffset + fDepth*(scale(fLightAngle) - scale(fCameraAngle))); vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI)); v3FrontColor += v3Attenuate * (fDepth * fScaledLength); v3SamplePoint += v3SampleRay; } gg_FrontSecondaryColor.rgb = v3FrontColor * fKmESun; gg_FrontColor.rgb = v3FrontColor * (v3InvWavelength * fKrESun); gl_Position = MVP * vec4(vertexPosition_modelspace,1); v3Direction = v3CameraPos - v3Pos; } Fragment Shader: #version 330 core uniform vec3 v3LightPos; uniform float g; uniform float g2; in vec3 v3Direction; out vec4 FragColor; in vec4 gg_FrontColor; in vec4 gg_FrontSecondaryColor; void main (void) { float fCos = dot(v3LightPos, v3Direction) / length(v3Direction); float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5); FragColor = gg_FrontColor + fMiePhase * gg_FrontSecondaryColor; FragColor.a = FragColor.b; } I wrote a function to render a sphere, and im trying to render this shader onto a inverted version of it, the sphere works completely fine, with normals and all. My problem is that the sphere gets rendered all black, so the shader is not working. This is how i'm trying to render the atmosphere inside my main rendering loop. glUseProgram(programAtmosphere); glBindTexture(GL_TEXTURE_2D, 0); //###################### glUniform3f(v3CameraPos, getPlayerPos().x, getPlayerPos().y, getPlayerPos().z); glUniform3f(v3LightPos, lightPos.x / sqrt(lightPos.x * lightPos.x + lightPos.y * lightPos.y), lightPos.y / sqrt(lightPos.x * lightPos.x + lightPos.y * lightPos.y), 0); glUniform3f(v3InvWavelength, 1.0 / pow(0.650, 4.0), 1.0 / pow(0.570, 4.0), 1.0 / pow(0.475, 4.0)); glUniform1fARB(fCameraHeight, 1); glUniform1fARB(fCameraHeight2, 1); glUniform1fARB(fInnerRadius, 6350); glUniform1fARB(fInnerRadius2, 6350 * 6350); glUniform1fARB(fOuterRadius, 6450); glUniform1fARB(fOuterRadius2, 6450 * 6450); glUniform1fARB(fKrESun, 0.0025 * 20.0); glUniform1fARB(fKmESun, 0.0015 * 20.0); glUniform1fARB(fKr4PI, 0.0025 * 4.0 * 3.141592653); glUniform1fARB(fKm4PI, 0.0015 * 4.0 * 3.141592653); glUniform1fARB(fScale, 1.0 / (6450 - 6350)); glUniform1fARB(fScaleDepth, 0.25); glUniform1fARB(fScaleOverScaleDepth, 4.0 / (6450 - 6350)); glUniform1fARB(g, -0.85); glUniform1f(g2, -0.85 * -0.85); // vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[1]); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[1]); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer[1]); glUniformMatrix4fv(ModelMatrixAT, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixAT, 1, GL_FALSE, &ViewMatrix[0][0]); glUniformMatrix4fv(ModelViewPAT, 1, GL_FALSE, &MVP[0][0]); // Draw the triangles glDrawElements( GL_TRIANGLES, // mode cubeIndices[1], // count GL_UNSIGNED_SHORT, // type (void*)0 // element array buffer offset ); Any ideas?

    Read the article

  • Can't get Jacobi algorithm to work in Objective-C

    - by Chris Long
    Hi, For some reason, I can't get this program to work. I've had other CS majors look at it and they can't figure it out either. This program performs the Jacobi algorithm (you can see step-by-step instructions and a MATLAB implementation here). BTW, it's different from the Wikipedia article of the same name. Since NSArray is one-dimensional, I added a method that makes it act like a two-dimensional C array. After running the Jacobi algorithm many times, the diagonal entries in the NSArray (i[0][0], i[1][1], etc.) are supposed to get bigger and the others approach 0. For some reason though, they all increase exponentially. For instance, i[2][4] should equal 0.0000009, not 9999999, while i[2][2] should be big. Thanks in advance, Chris NSArray+Matrix.m @implementation NSArray (Matrix) @dynamic offValue, transposed; - (double)offValue { double sum = 0.0; for ( MatrixItem *item in self ) if ( item.nonDiagonal ) sum += pow( item.value, 2.0 ); return sum; } - (NSMutableArray *)transposed { NSMutableArray *transpose = [[[NSMutableArray alloc] init] autorelease]; int i, j; for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 5; j++ ) { [transpose addObject:[self objectAtRow:j andColumn:i]]; } } return transpose; } - (id)objectAtRow:(NSUInteger)row andColumn:(NSUInteger)column { NSUInteger index = 5 * row + column; return [self objectAtIndex:index]; } - (NSMutableArray *)multiplyWithMatrix:(NSArray *)array { NSMutableArray *result = [[NSMutableArray alloc] init]; int i = 0, j = 0, k = 0; double value; for ( i = 0; i < 5; i++ ) { value = 0.0; for ( j = 0; j < 5; j++ ) { for ( k = 0; k < 5; k++ ) { MatrixItem *firstItem = [self objectAtRow:i andColumn:k]; MatrixItem *secondItem = [array objectAtRow:k andColumn:j]; value += firstItem.value * secondItem.value; } MatrixItem *item = [[MatrixItem alloc] initWithValue:value]; item.row = i; item.column = j; [result addObject:item]; } } return result; } @end Jacobi_AlgorithmAppDelegate.m // ... - (void)jacobiAlgorithmWithEntry:(MatrixItem *)entry { MatrixItem *b11 = [matrix objectAtRow:entry.row andColumn:entry.row]; MatrixItem *b22 = [matrix objectAtRow:entry.column andColumn:entry.column]; double muPlus = ( b22.value + b11.value ) / 2.0; muPlus += sqrt( pow((b22.value - b11.value), 2.0) + 4.0 * pow(entry.value, 2.0) ); Vector *u1 = [[[Vector alloc] initWithX:(-1.0 * entry.value) andY:(b11.value - muPlus)] autorelease]; [u1 normalize]; Vector *u2 = [[[Vector alloc] initWithX:-u1.y andY:u1.x] autorelease]; NSMutableArray *g = [[[NSMutableArray alloc] init] autorelease]; for ( int i = 0; i <= 24; i++ ) { MatrixItem *item = [[[MatrixItem alloc] init] autorelease]; if ( i == 6*entry.row ) item.value = u1.x; else if ( i == 6*entry.column ) item.value = u2.y; else if ( i == ( 5*entry.row + entry.column ) || i == ( 5*entry.column + entry.row ) ) item.value = u1.y; else if ( i % 6 == 0 ) item.value = 1.0; else item.value = 0.0; [g addObject:item]; } NSMutableArray *firstResult = [[g.transposed multiplyWithMatrix:matrix] autorelease]; matrix = [firstResult multiplyWithMatrix:g]; } // ...

    Read the article

  • Java code optimization leads to numerical inaccuracies and errors

    - by rano
    I'm trying to implement a version of the Fuzzy C-Means algorithm in Java and I'm trying to do some optimization by computing just once everything that can be computed just once. This is an iterative algorithm and regarding the updating of a matrix, the clusters x pixels membership matrix U, this is the update rule I want to optimize: where the x are the element of a matrix X (pixels x features) and v belongs to the matrix V (clusters x features). And m is a parameter that ranges from 1.1 to infinity. The distance used is the euclidean norm. If I had to implement this formula in a banal way I'd do: for(int i = 0; i < X.length; i++) { int count = 0; for(int j = 0; j < V.length; j++) { double num = D[i][j]; double sumTerms = 0; for(int k = 0; k < V.length; k++) { double thisDistance = D[i][k]; sumTerms += Math.pow(num / thisDistance, (1.0 / (m - 1.0))); } U[i][j] = (float) (1f / sumTerms); } } In this way some optimization is already done, I precomputed all the possible squared distances between X and V and stored them in a matrix D but that is not enough, since I'm cycling througn the elements of V two times resulting in two nested loops. Looking at the formula the numerator of the fraction is independent of the sum so I can compute numerator and denominator independently and the denominator can be computed just once for each pixel. So I came to a solution like this: int nClusters = V.length; double exp = (1.0 / (m - 1.0)); for(int i = 0; i < X.length; i++) { int count = 0; for(int j = 0; j < nClusters; j++) { double distance = D[i][j]; double denominator = D[i][nClusters]; double numerator = Math.pow(distance, exp); U[i][j] = (float) (1f / (numerator * denominator)); } } Where I precomputed the denominator into an additional column of the matrix D while I was computing the distances: for (int i = 0; i < X.length; i++) { for (int j = 0; j < V.length; j++) { double sum = 0; for (int k = 0; k < nDims; k++) { final double d = X[i][k] - V[j][k]; sum += d * d; } D[i][j] = sum; D[i][B.length] += Math.pow(1 / D[i][j], exp); } } By doing so I encounter numerical differences between the 'banal' computation and the second one that leads to different numerical value in U (not in the first iterates but soon enough). I guess that the problem is that exponentiate very small numbers to high values (the elements of U can range from 0.0 to 1.0 and exp , for m = 1.1, is 10) leads to ver y small values, whereas by dividing the numerator and the denominator and THEN exponentiating the result seems to be better numerically. The problem is it involves much more operations. Am I doing something wrong? Is there a possible solution to get both the code optimized and numerically stable? Any suggestion or criticism will be appreciated.

    Read the article

  • Incorrect lighting results with deferred rendering

    - by Lasse
    I am trying to render a light-pass to a texture which I will later apply on the scene. But I seem to calculate the light position wrong. I am working on view-space. In the image above, I am outputting the attenuation of a point light which is currently covering the whole screen. The light is at 0,10,0 position, and I transform it to view-space first: Vector4 pos; Vector4 tmp = new Vector4 (light.Position, 1); // Transform light position for shader Vector4.Transform (ref tmp, ref Camera.ViewMatrix, out pos); shader.SendUniform ("LightViewPosition", ref pos); Now to me that does not look as it should. What I think it should look like is that the white area should be on the center of the scene. The camera is at the corner of the scene, and it seems as if the light would move along with the camera. Here's the fragment shader code: void main(){ // default black color vec3 color = vec3(0); // Pixel coordinates on screen without depth vec2 PixelCoordinates = gl_FragCoord.xy / ScreenSize; // Get pixel position using depth from texture vec4 depthtexel = texture( DepthTexture, PixelCoordinates ); float depthSample = unpack_depth(depthtexel); // Get pixel coordinates on camera-space by multiplying the // coordinate on screen-space by inverse projection matrix vec4 world = (ImP * RemapMatrix * vec4(PixelCoordinates, depthSample, 1.0)); // Undo the perspective calculations vec3 pixelPosition = (world.xyz / world.w) * 3; // How far the light should reach from it's point of origin float lightReach = LightColor.a / 2; // Vector in between light and pixel vec3 lightDir = (LightViewPosition.xyz - pixelPosition); float lightDistance = length(lightDir); vec3 lightDirN = normalize(lightDir); // Discard pixels too far from light source //if(lightReach < lightDistance) discard; // Get normal from texture vec3 normal = normalize((texture( NormalTexture, PixelCoordinates ).xyz * 2) - 1); // Half vector between the light direction and eye, used for specular component vec3 halfVector = normalize(lightDirN + normalize(-pixelPosition)); // Dot product of normal and light direction float NdotL = dot(normal, lightDirN); float attenuation = pow(lightReach / lightDistance, LightFalloff); // If pixel is lit by the light if(NdotL > 0) { // I have moved stuff from here to above so I can debug them. // Diffuse light color color += LightColor.rgb * NdotL * attenuation; // Specular light color color += LightColor.xyz * pow(max(dot(halfVector, normal), 0.0), 4.0) * attenuation; } RT0 = vec4(color, 1); //RT0 = vec4(pixelPosition, 1); //RT0 = vec4(depthSample, depthSample, depthSample, 1); //RT0 = vec4(NdotL, NdotL, NdotL, 1); RT0 = vec4(attenuation, attenuation, attenuation, 1); //RT0 = vec4(lightReach, lightReach, lightReach, 1); //RT0 = depthtexel; //RT0 = 100 / vec4(lightDistance, lightDistance, lightDistance, 1); //RT0 = vec4(lightDirN, 1); //RT0 = vec4(halfVector, 1); //RT0 = vec4(LightColor.xyz,1); //RT0 = vec4(LightViewPosition.xyz/100, 1); //RT0 = vec4(LightPosition.xyz, 1); //RT0 = vec4(normal,1); } What am I doing wrong here?

    Read the article

  • Prevent full table scan for query with multiple where clauses

    - by Dave Jarvis
    A while ago I posted a message about optimizing a query in MySQL. I have since ported the data and query to PostgreSQL, but now PostgreSQL has the same problem. The solution in MySQL was to force the optimizer to not optimize using STRAIGHT_JOIN. PostgreSQL offers no such option. Here is the explain: Here is the query: SELECT avg(d.amount) AS amount, y.year FROM station s, station_district sd, year_ref y, month_ref m, daily d LEFT JOIN city c ON c.id = 10663 WHERE -- Find all the stations within a specific unit radius ... -- 6371.009 * SQRT( POW(RADIANS(c.latitude_decimal - s.latitude_decimal), 2) + (COS(RADIANS(c.latitude_decimal + s.latitude_decimal) / 2) * POW(RADIANS(c.longitude_decimal - s.longitude_decimal), 2)) ) <= 50 AND -- Ignore stations outside the given elevations -- s.elevation BETWEEN 0 AND 2000 AND sd.id = s.station_district_id AND -- Gather all known years for that station ... -- y.station_district_id = sd.id AND -- The data before 1900 is shaky; insufficient after 2009. -- y.year BETWEEN 1980 AND 2000 AND -- Filtered by all known months ... -- m.year_ref_id = y.id AND m.month = 12 AND -- Whittled down by category ... -- m.category_id = '001' AND -- Into the valid daily climate data. -- m.id = d.month_ref_id AND d.daily_flag_id <> 'M' GROUP BY y.year It appears as though PostgreSQL is looking at the DAILY table first, which is simply not the right way to go about this query as there are nearly 300 million rows. How do I force PostgreSQL to start at the CITY table? Thank you!

    Read the article

  • Why does division yield a vastly different result than multiplication by a fraction in floating points.

    - by Avram
    I understand why floating point numbers can't be compared, and know about the mantissa and exponent binary representation, but I'm no expert and today I came across something I don't get: Namely lets say you have something like: float denominator, numerator, resultone, resulttwo; resultone = numerator / denominator; float buff = 1 / denominator; resulttwo = numerator * buff; To my knowledge different flops can yield different results and this is not unusual. But in some edge cases these two results seem to be vastly different. To be more specific in my GLSL code calculating the Beckmann facet slope distribution for the Cook-Torrance lighitng model: float a = 1 / (facetSlopeRMS * facetSlopeRMS * pow(clampedCosHalfNormal, 4)); float b = clampedCosHalfNormal * clampedCosHalfNormal - 1.0; float c = facetSlopeRMS * facetSlopeRMS * clampedCosHalfNormal * clampedCosHalfNormal; facetSlopeDistribution = a * exp(b/c); yields very very different results to float a = (facetSlopeRMS * facetSlopeRMS * pow(clampedCosHalfNormal, 4)); facetDlopeDistribution = exp(b/c) / a; Why does it? The second form of the expression is problematic. If I say try to add the second form of the expression to a color I get blacks, even though the expression should always evaluate to a positive number. Am I getting an infinity? A NaN? if so why?

    Read the article

  • Beginner problems with references to arrays in python 3.1.1

    - by Protean
    As part of the last assignment in a beginner python programing class, I have been assigned a traveling sales man problem. I settled on a recursive function to find each permutation and the sum of the distances between the destinations, however, I am have a lot of problems with references. Arrays in different instances of the Permute and Main functions of TSP seem to be pointing to the same reference. from math import sqrt class TSP: def __init__(self): self.CartisianCoordinates = [['A',[1,1]], ['B',[2,2]], ['C',[2,1]], ['D',[1,2]], ['E',[3,3]]] self.Array = [] self.Max = 0 self.StoredList = ['',0] def Distance(self, i1, i2): x1 = self.CartisianCoordinates[i1][1][0] y1 = self.CartisianCoordinates[i1][1][1] x2 = self.CartisianCoordinates[i2][1][0] y2 = self.CartisianCoordinates[i2][1][1] return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)) def Evaluate(self): temparray = [] Data = [] for i in range(len(self.CartisianCoordinates)): Data.append([]) for i1 in range(len(self.CartisianCoordinates)): for i2 in range(len(self.CartisianCoordinates)): if i1 != i2: temparray.append(self.Distance(i1, i2)) else: temparray.append('X') Data[i1] = temparray temparray = [] self.Array = Data self.Max = len(Data) def Permute(self,varray,index,vcarry,mcarry): #Problem Class array = varray[:] carry = vcarry[:] for i in range(self.Max): print ('ARRAY:', array) print (index,i,carry,array[index][i]) if array[index][i] != 'X': carry[0] += self.CartisianCoordinates[i][0] carry[1] += array[index][i] if len(carry) != self.Max: temparray = array[:] for j in range(self.Max):temparray[j][i] = 'X' index = i mcarry += self.Permute(temparray,index,carry,mcarry) else: return mcarry print ('pass',mcarry) return mcarry def Main(self): out = [] self.Evaluate() for i in range(self.Max): array = self.Array[:] #array appears to maintain the same reference after each copy, resulting in an incorrect array being passed to Permute after the first iteration. print (self.Array[:]) for j in range(self.Max):array[j][i] = 'X' print('I:', i, array) out.append(self.Permute(array,i,[str(self.CartisianCoordinates[i][0]),0],[])) return out SalesPerson = TSP() print(SalesPerson.Main()) It would be greatly appreciated if you could provide me with help in solving the reference problems I am having. Thank you.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >