Search Results

Search found 3425 results on 137 pages for 'polynomial math'.

Page 9/137 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • C# Collision Math Help

    - by user36037
    I am making my own collision detection in MonoGame. I have a PolyLine class That has a property to return the normal of that PolyLine instance. I have a ConvexPolySprite class that has a List LineSegments. I hav a CircleSprite class that has a Center Property and a Radius Property. I am using a static class for the collision detection method. I am testing it on a single line segment. Vector2(200,0) = Vector2(300, 200) The problem is it detects the collision anywhere along the path of line out into space. I cannot figure out why. Thanks in advance; public class PolyLine { //--------------------------------------------------------------------------------------------------------------------------- // Class Properties /// <summary> /// Property for the upper left-hand corner of the owner of this instance /// </summary> public Vector2 ParentPosition { get; set; } /// <summary> /// Relative start point of the line segment /// </summary> public Vector2 RelativeStartPoint { get; set; } /// <summary> /// Relative end point of the line segment /// </summary> public Vector2 RelativeEndPoint { get; set; } /// <summary> /// Property that gets the absolute position of the starting point of the line segment /// </summary> public Vector2 AbsoluteStartPoint { get { return ParentPosition + RelativeStartPoint; } }//end of AbsoluteStartPoint /// <summary> /// Gets the absolute position of the end point of the line segment /// </summary> public Vector2 AbsoluteEndPoint { get { return ParentPosition + RelativeEndPoint; } }//end of AbsoluteEndPoint public Vector2 NormalizedLeftNormal { get { Vector2 P = AbsoluteEndPoint - AbsoluteStartPoint; P.Normalize(); float x = P.X; float y = P.Y; return new Vector2(-y, x); } }//end of NormalizedLeftNormal //--------------------------------------------------------------------------------------------------------------------------- // Class Constructors /// <summary> /// Sole ctor /// </summary> /// <param name="parentPosition"></param> /// <param name="relStart"></param> /// <param name="relEnd"></param> public PolyLine(Vector2 parentPosition, Vector2 relStart, Vector2 relEnd) { ParentPosition = parentPosition; RelativeEndPoint = relEnd; RelativeStartPoint = relStart; }//end of ctor }//end of PolyLine class public static bool Collided(CircleSprite circle, ConvexPolygonSprite poly) { var distance = Vector2.Dot(circle.Position - poly.LineSegments[0].AbsoluteEndPoint, poly.LineSegments[0].NormalizedLeftNormal) + circle.Radius; if (distance <= 0) { return false; } else { return true; } }//end of collided

    Read the article

  • Create Math Game with PHP, Ajax, Jquery

    - by Sambucasun
    I am developing a website where user can create their own game which can be joined by other users as well. It's a simple maths game which will shoot equations based on time or count specified. I want that moment user create a game, it will be listed in "current Games" section. Other users can check out the list and select the game to join. After game is created, creater should have a screen which should be having his name with display pic. Now gradually as others start joining the game, list should updated automatically. Once enough users are there i will start the game. The same list should be displayed to other users who join the game. Once game is over all will be displayed a summary list. I have gone through couple of threads but could not get clear idea. Do I need to use comet or other technology to create such game or simple PHP, Ajax or Jquery will suffice ? Also I want my website should be mobile compatible so i am designing it in html5. If i create this game using just Ajax then will there be any performance issue while playing through mobile. I am not much experienced so just need guidance for what should be appropriate or use for my requirement.

    Read the article

  • Help on understanding JS

    - by Anonymous
    I have thos piece of code: Math&&Math.random?Math.floor(Math.random()*10000000000000):Date.getTime(); And as far as i know && is logic operator for AND, so im trying to convert this into PHP and this is where i got: intval(floor(time()/10800000)%10+(rand()?floor(rand()*10000000000000):time())) The problem is that i can't understand the first part Math&& Can anyone help with this one cause i always get negative result, when i should get positive (probably the logic rand-time is not working in my php example)

    Read the article

  • question about polynomial multiplication

    - by davit-datuashvili
    i know that horners method for polynomial pultiplication is faster but here i dont know what is happening here is code public class horner{ public static final int n=10; public static final int x=7; public static void main(String[] args){ //non fast version int a[]=new int[]{1,2,3,4,5,6,7,8,9,10}; int xi=1; int y=a[0]; for (int i=1;i<n;i++){ xi=x*xi; y=y+a[i]*xi; } System.out.println(y); //fast method int y1=a[n-1]; for (int i=n-2;i>=0;i--){ y1=x*y+a[i]; } System.out.println(y1); } } result of this two methods are not same result of first method is 462945547 and result of second method is -1054348465 please help

    Read the article

  • My raycaster is putting out strange results, how do I fix it?

    - by JamesK89
    I'm working on a raycaster in ActionScript 3.0 for the fun of it, and as a learning experience. I've got it up and running and its displaying me output as expected however I'm getting this strange bug where rays go through corners of blocks and the edges of blocks appear through walls. Maybe somebody with more experience can point out what I'm doing wrong or maybe a fresh pair of eyes can spot a tiny bug I haven't noticed. Thank you so much for your help! Screenshots: http://i55.tinypic.com/25koebm.jpg http://i51.tinypic.com/zx5jq9.jpg Relevant code: function drawScene() { rays.graphics.clear(); rays.graphics.lineStyle(1, rgba(0x00,0x66,0x00)); var halfFov = (player.fov/2); var numRays:int = ( stage.stageWidth / COLUMN_SIZE ); var prjDist = ( stage.stageWidth / 2 ) / Math.tan(toRad( halfFov )); var angStep = ( player.fov / numRays ); for( var i:int = 0; i < numRays; i++ ) { var rAng = ( ( player.angle - halfFov ) + ( angStep * i ) ) % 360; if( rAng < 0 ) rAng += 360; var ray:Object = castRay(player.position, rAng); drawRaySlice(i*COLUMN_SIZE, prjDist, player.angle, ray); } } function drawRaySlice(sx:int, prjDist, angle, ray:Object) { if( ray.distance >= MAX_DIST ) return; var height:int = int(( TILE_SIZE / (ray.distance * Math.cos(toRad(angle-ray.angle))) ) * prjDist); if( !height ) return; var yTop = int(( stage.stageHeight / 2 ) - ( height / 2 )); if( yTop < 0 ) yTop = 0; var yBot = int(( stage.stageHeight / 2 ) + ( height / 2 )); if( yBot > stage.stageHeight ) yBot = stage.stageHeight; rays.graphics.moveTo( (ray.origin.x / TILE_SIZE) * MINI_SIZE, (ray.origin.y / TILE_SIZE) * MINI_SIZE ); rays.graphics.lineTo( (ray.hit.x / TILE_SIZE) * MINI_SIZE, (ray.hit.y / TILE_SIZE) * MINI_SIZE ); for( var x:int = 0; x < COLUMN_SIZE; x++ ) { for( var y:int = yTop; y < yBot; y++ ) { buffer.setPixel(sx+x, y, clrTable[ray.tile-1] >> ( ray.horz ? 1 : 0 )); } } } function castRay(origin:Point, angle):Object { // Return values var rTexel = 0; var rHorz = false; var rTile = 0; var rDist = MAX_DIST + 1; var rMap:Point = new Point(); var rHit:Point = new Point(); // Ray angle and slope var ra = toRad(angle) % ANGLE_360; if( ra < ANGLE_0 ) ra += ANGLE_360; var rs = Math.tan(ra); var rUp = ( ra > ANGLE_0 && ra < ANGLE_180 ); var rRight = ( ra < ANGLE_90 || ra > ANGLE_270 ); // Ray position var rx = 0; var ry = 0; // Ray step values var xa = 0; var ya = 0; // Ray position, in map coordinates var mx:int = 0; var my:int = 0; var mt:int = 0; // Distance var dx = 0; var dy = 0; var ds = MAX_DIST + 1; // Horizontal intersection if( ra != ANGLE_180 && ra != ANGLE_0 && ra != ANGLE_360 ) { ya = ( rUp ? TILE_SIZE : -TILE_SIZE ); xa = ya / rs; ry = int( origin.y / TILE_SIZE ) * ( TILE_SIZE ) + ( rUp ? TILE_SIZE : -1 ); rx = origin.x + ( ry - origin.y ) / rs; mx = 0; my = 0; while( mx >= 0 && my >= 0 && mx < world.size.x && my < world.size.y ) { mx = int( rx / TILE_SIZE ); my = int( ry / TILE_SIZE ); mt = getMapTile(mx,my); if( mt > 0 && mt < 9 ) { dx = rx - origin.x; dy = ry - origin.y; ds = ( dx * dx ) + ( dy * dy ); if( rDist >= MAX_DIST || ds < rDist ) { rDist = ds; rTile = mt; rMap.x = mx; rMap.y = my; rHit.x = rx; rHit.y = ry; rHorz = true; rTexel = int(rx % TILE_SIZE) } break; } rx += xa; ry += ya; } } // Vertical intersection if( ra != ANGLE_90 && ra != ANGLE_270 ) { xa = ( rRight ? TILE_SIZE : -TILE_SIZE ); ya = xa * rs; rx = int( origin.x / TILE_SIZE ) * ( TILE_SIZE ) + ( rRight ? TILE_SIZE : -1 ); ry = origin.y + ( rx - origin.x ) * rs; mx = 0; my = 0; while( mx >= 0 && my >= 0 && mx < world.size.x && my < world.size.y ) { mx = int( rx / TILE_SIZE ); my = int( ry / TILE_SIZE ); mt = getMapTile(mx,my); if( mt > 0 && mt < 9 ) { dx = rx - origin.x; dy = ry - origin.y; ds = ( dx * dx ) + ( dy * dy ); if( rDist >= MAX_DIST || ds < rDist ) { rDist = ds; rTile = mt; rMap.x = mx; rMap.y = my; rHit.x = rx; rHit.y = ry; rHorz = false; rTexel = int(ry % TILE_SIZE); } break; } rx += xa; ry += ya; } } return { angle: angle, distance: Math.sqrt(rDist), hit: rHit, map: rMap, tile: rTile, horz: rHorz, origin: origin, texel: rTexel }; }

    Read the article

  • Complex.pm taking up a lot of time

    - by synapz
    While trying to profile my perl program, I find that Complex.pm is taking up a lot of time with what looks like some kind of warning. Also, my code shouldn't have any complex numbers being generated or used, so I am not sure what it is doing in Complex.pm, anyway. Here's the FastProf output for the most expensive lines: /usr/lib/perl5/5.8.8/Math/Complex.pm:182 1.55480 276232: _cannot_make("real part", $re) unless $re =~ /^$gre$/; /usr/lib/perl5/5.8.8/Math/Complex.pm:310 1.01132 453641: sub cartesian {$_[0]->{c_dirty} ? /usr/lib/perl5/5.8.8/Math/Complex.pm:315 0.97497 562188: sub set_cartesian { $_[0]->{p_dirty}++; $_[0]->{c_dirty} = 0; /usr/lib/perl5/5.8.8/Math/Complex.pm:189 0.86302 276232: return $self; /usr/lib/perl5/5.8.8/Math/Complex.pm:1332 0.85628 293660: $self->{display_format} = { %display_format }; /usr/lib/perl5/5.8.8/Math/Complex.pm:185 0.81529 276232: _cannot_make("imaginary part", $im) unless $im =~ /^$gre$/; /usr/lib/perl5/5.8.8/Math/Complex.pm:1316 0.78749 293660: my %display_format = %DISPLAY_FORMAT; /usr/lib/perl5/5.8.8/Math/Complex.pm:1335 0.69534 293660: %{$self->{display_format}} : /usr/lib/perl5/5.8.8/Math/Complex.pm:186 0.66697 276232: $self->set_cartesian([$re, $im ]); /usr/lib/perl5/5.8.8/Math/Complex.pm:170 0.62790 276232: my $self = bless {}, shift; /usr/lib/perl5/5.8.8/Math/Complex.pm:172 0.56733 276232: if (@_ == 0) { /usr/lib/perl5/5.8.8/Math/Complex.pm:316 0.53179 281094: $_[0]->{'cartesian'} = $_[1] } /usr/lib/perl5/5.8.8/Math/Complex.pm:1324 0.48768 293660: if (@_ == 1) { /usr/lib/perl5/5.8.8/Math/Complex.pm:1319 0.44835 293660: if (exists $self->{display_format}) { /usr/lib/perl5/5.8.8/Math/Complex.pm:1318 0.40355 293660: if (ref $self) { # Called as an object method /usr/lib/perl5/5.8.8/Math/Complex.pm:187 0.39950 276232: $self->display_format('cartesian'); /usr/lib/perl5/5.8.8/Math/Complex.pm:1315 0.39312 293660: my $self = shift; /usr/lib/perl5/5.8.8/Math/Complex.pm:1331 0.38087 293660: if (ref $self) { # Called as an object method /usr/lib/perl5/5.8.8/Math/Complex.pm:184 0.35171 276232: $im ||= 0; /usr/lib/perl5/5.8.8/Math/Complex.pm:181 0.34145 276232: if (defined $re) { /usr/lib/perl5/5.8.8/Math/Complex.pm:171 0.33492 276232: my ($re, $im); /usr/lib/perl5/5.8.8/Math/Complex.pm:390 0.20658 128280: my ($z1, $z2, $regular) = @_; /usr/lib/perl5/5.8.8/Math/Complex.pm:391 0.20631 128280: if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) { Thanks for any help!

    Read the article

  • Why does the BigFraction class in the Apache-Commons-Math library return incorrect division results?

    - by Timothy Lee Russell
    In the spirit of using existing, tested and stable libraries of code, I started using the Apache-Commons-Math library and its BigFraction class to perform some rational calculations for an Android app I'm writing called RationalCalc. It works great for every task that I have thrown at it, except for one nagging problem. When dividing certain BigFraction values, I am getting incorrect results. If I create a BigFraction with the inverse of the divisor and multiply instead, I get the same incorrect answer but perhaps that is what the library is doing internally anyway. Does anyone know what I am doing wrong? The division works correctly with a BigFraction of 2.5 but not 2.51, 2.49, etc... // *** incorrect! *** BigFraction one = new BigFraction(1.524); //one: 1715871458028159 / 1125899906842624 BigFraction two = new BigFraction(2.51); //two: 1413004383087493 / 562949953421312 BigFraction three = one.divide(two); //three: 0 Log.i("solve", three.toString()); //should be 0.607171315 ?? //returns 0 // *** correct! **** BigFraction four = new BigFraction(1.524); //four: 1715871458028159 / 1125899906842624 BigFraction five = new BigFraction(2.5); //five: 5 / 2 BigFraction six = four.divide(five); //six: 1715871458028159 / 2814749767106560 Log.i("solve", six.toString()); //should be 0.6096 ?? //returns 0.6096

    Read the article

  • Getting a handle on GIS math, where do I start?

    - by Joshua
    I am in charge of a program that is used to create a set of nodes and paths for consumption by an autonomous ground vehicle. The program keeps track of the locations of all items in its map by indicating the item's position as being x meters north and y meters east of an origin point of 0,0. In the real world, the vehicle knows the location of the origin's lat and long, as it is determined by a dgps system and is accurate down to a couple centimeters. My program is ignorant of any lat long coordinates. It is one of my goals to modify the program to keep track of lat long coords of items in addition to an origin point and items' x,y position in relation to that origin. At first blush, it seems that I am going to modify the program to allow the lat long coords of the origin to be passed in, and after that I desire that the program will automatically calculate the lat long of every item currently in a map. From what I've researched so far, I believe that I will need to figure out the math behind converting to lat long coords from a UTM like projection where I specify the origin points and meridians etc as opposed to whatever is defined already for UTM. I've come to ask of you GIS programmers, am I on the right track? It seems to me like there is so much to wrap ones head around, and I'm not sure if the answer isn't something as simple as, "oh yea theres a conversion from meters to lat long, here" Currently, due to the nature of DGPS, the system really doesn't need to care about locations more than oh, what... 40 km? radius away from the origin. Given this, and the fact that I need to make sure that the error on my coordinates is not greater than .5 meters, do I need anything more complex than a simple lat/long to meters conversion constant? I'm knee deep in materials here. I could use some pointers about what concepts to research. Thanks much!

    Read the article

  • Adding Polynomials (Linked Lists)......Bug Help

    - by Brian
    I have written a program that creates nodes that in this class are parts of polynomials and then the two polynomials get added together to become one polynomial (list of nodes). All my code compiles so the only problem I am having is that the nodes are not inserting into the polynomial via the insert method I have in polynomial.java and when running the program it does create nodes and displays them in the 2x^2 format but when it comes to add the polynomials together it displays o as the polynomials, so if anyone can figure out whats wrong and what I can do to fix it it would be much appreciated. Here is the code: import java.util.Scanner; class Polynomial{ public termNode head; public Polynomial() { head = null; } public boolean isEmpty() { return (head == null); } public void display() { if (head == null) System.out.print("0"); else for(termNode cur = head; cur != null; cur = cur.getNext()) { System.out.println(cur); } } public void insert(termNode newNode) { termNode prev = null; termNode cur = head; while (cur!=null && (newNode.compareTo(cur)<0)) { prev = null; cur = cur.getNext(); } if (prev == null) { newNode.setNext(head); head = newNode; } else { newNode.setNext(cur); prev.setNext(newNode); } } public void readPolynomial(Scanner kb) { boolean done = false; double coefficient; int exponent; termNode term; head = null; //UNLINK ANY PREVIOUS POLYNOMIAL System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient == 0 && exponent == 0); while(!done) { Polynomial poly = new Polynomial(); term = new termNode(coefficient,exponent); System.out.println(term); poly.insert(term); System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient==0 && exponent==0); } } public static Polynomial add(Polynomial p, Polynomial q) { Polynomial r = new Polynomial(); double coefficient; int exponent; termNode first = p.head; termNode second = q.head; termNode sum = r.head; termNode term; while (first != null && second != null) { if (first.getExp() == second.getExp()) { if (first.getCoeff() != 0 && second.getCoeff() != 0); { double addCoeff = first.getCoeff() + second.getCoeff(); term = new termNode(addCoeff,first.getExp()); sum.setNext(term); first.getNext(); second.getNext(); } } else if (first.getExp() < second.getExp()) { sum.setNext(second); term = new termNode(second.getCoeff(),second.getExp()); sum.setNext(term); second.getNext(); } else { sum.setNext(first); term = new termNode(first.getNext()); sum.setNext(term); first.getNext(); } } while (first != null) { sum.setNext(first); } while (second != null) { sum.setNext(second); } return r; } } Here is my Node class: class termNode implements Comparable { private int exp; private double coeff; private termNode next; public termNode(double coefficient, int exponent) { coeff = coefficient; exp = exponent; next = null; } public termNode(termNode inTermNode) { coeff = inTermNode.coeff; exp = inTermNode.exp; } public void setData(double coefficient, int exponent) { coefficient = coeff; exponent = exp; } public double getCoeff() { return coeff; } public int getExp() { return exp; } public void setNext(termNode link) { next = link; } public termNode getNext() { return next; } public String toString() { if (exp == 0) { return(coeff + " "); } else if (exp == 1) { return(coeff + "x"); } else { return(coeff + "x^" + exp); } } public int compareTo(Object other) { if(exp ==((termNode) other).exp) return 0; else if(exp < ((termNode) other).exp) return -1; else return 1; } } And here is my Test class to run the program. import java.util.Scanner; class PolyTest{ public static void main(String [] args) { Scanner kb = new Scanner(System.in); Polynomial r; Polynomial p = new Polynomial(); System.out.println("Enter first polynomial."); p.readPolynomial(kb); Polynomial q = new Polynomial(); System.out.println(); System.out.println("Enter second polynomial."); q.readPolynomial(kb); r = Polynomial.add(p,q); System.out.println(); System.out.print("The sum of "); p.display(); System.out.print(" and "); q.display(); System.out.print(" is "); r.display(); } }

    Read the article

  • Can you help me optimize this code for finding factors of a number? I'm brushing up on my math progr

    - by Sergio Tapia
    I've never really bothered with math programming, but today I've decided to give it a shot. Here's my code and it's working as intended: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PrimeFactorization { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnSubmit_Click(object sender, RoutedEventArgs e) { List<int> primeFactors = FindPrimeFactors(Convert.ToInt32(txtNumber.Text)); primeFactors.Sort(); for (int i = 0; i < primeFactors.Count; i++) { listBoxFoundNumbers.Items.Add(primeFactors[i]); } } private List<int> FindPrimeFactors(int number) { List<int> factors = new List<int>(); factors.Add(1); factors.Add(number); for (int i = 2; i < number; i++) { if (number % i == 0) { int holder = number / i; //If the number is in the list, don't add it again. if (!factors.Contains(i)) { factors.Add(i); } //If the number is in the list, don't add it again. if (!factors.Contains(holder)) { factors.Add(holder); } } } return factors; } } } The only problem I can see with my code is that it will iterate through to the bitter end, even though there will definitely not be any factors. For example, imagine I wrote in 35. My loop will go up to 35 and check 24,25,26,27...etc. Not very good. What do you recommend?

    Read the article

  • Isometric Movement in Javascript In the DOM

    - by deep
    I am creating a game using Javascript. I am not using the HTML5 Canvas Element. The game requires both side view controlles, and Isometric controls, hence the movementMode variable. I have got the specific angles, but I am stuck on an aspect of this. https://chillibyte.makes.org/thimble/movement function draw() { if (keyPressed) { if (whichKey == keys.left) { move(-1,0) } if (whichKey == keys.right) { move(1,0) } if (whichKey == keys.up) { move(0,-1) } if (whichKey == keys.down) { move(0,1) } } } This gives normal up, down , left, and right. i want to refactor this so that i can plugin two variables into the move() function, which will give the movement wanted. Now for the trig. /| / | / | y / | /a___| x Take This Right angled Triangle. given that x is 1, y must be equal to tan(a) That Seems right. However, when I do Math.tan(45), i get a number similar to 1.601. Why? To Sum up this question. I have a function, and i need a function which will converts an angle to a value, which will tell me the number of pixels that i need to go up by, if i only go across 1. Is it Math.tan that i want? or is it something else?

    Read the article

  • Matrices: Arrays or separate member variables?

    - by bjz
    I'm teaching myself 3D maths and in the process building my own rudimentary engine (of sorts). I was wondering what would be the best way to structure my matrix class. There are a few options: Separate member variables: struct Mat4 { float m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; // methods } A multi-dimensional array: struct Mat4 { float[4][4] m; // methods } An array of vectors struct Mat4 { Vec4[4] m; // methods } I'm guessing there would be positives and negatives to each. From 3D Math Primer for Graphics and Game Development, 2nd Edition p.155: Matrices use 1-based indices, so the first row and column are numbered 1. For example, a12 (read “a one two,” not “a twelve”) is the element in the first row, second column. Notice that this is different from programming languages such as C++ and Java, which use 0-based array indices. A matrix does not have a column 0 or row 0. This difference in indexing can cause some confusion if matrices are stored using an actual array data type. For this reason, it’s common for classes that store small, fixed size matrices of the type used for geometric purposes to give each element its own named member variable, such as float a11, instead of using the language’s native array support with something like float elem[3][3]. So that's one vote for method one. Is this really the accepted way to do things? It seems rather unwieldy if the only benefit would be sticking with the conventional math notation.

    Read the article

  • math library in gcc

    - by Betamoo
    I am writing a program on linux gcc... When I tried to include <math.h> I found that I need to link math library by using command gcc -lm But I am searching for another way to link the math library 'in code', that does not require the user to compile using any options.. Can gcc -lm be done in c code using #pragma or something? EDIT: I have changed -ml to -lm

    Read the article

  • Testing a quadratic equation

    - by user1201587
    I'm doing a code testing for a program that calculate the results for a quadratic equation I need to have test data for the following situation, when a is not zero and d positive there is two possibilities which are in the code below, I need to find an example for the first satiation when Math.abs(b / a - 200.0) < 1.0e-4 , all the values that I have tried, excute the second one caption= "Two roots"; if (Math.abs(b / a - 200.0) < 1.0e-4) { System.out.println("first one"); x1 = (-100.0 * (1.0 + Math.sqrt(1.0 - 1.0 / (10000.0 * a)))); x2 = (-100.0 * (1.0 - Math.sqrt(1.0 - 1.0 / (10000.0 * a)))); } else { System.out.println("secrst one"); x1 = (-b - Math.sqrt(d)) / (2.0 * a); x2 = (-b + Math.sqrt(d)) / (2.0 * a); } } }

    Read the article

  • What algorithm to use to fill a KenKen square board with cages?

    - by JimmyBoh
    I am working on recreating KenKen, a popular math puzzle involving a blank grid that is divided into "cages". Each cage is just a collection of adjacent squares and has a clue which is generally a number and an operand, shown below: What type of algorithm would be best to fill the square with cages? Assume the maximum number of cells per cage would be 3 and the board is 4x4 in size, like in the example above.

    Read the article

  • How to implement Horner's scheme for multivariate polynomials?

    - by gsreynolds
    Background I need to solve polynomials in multiple variables using Horner's scheme in Fortran90/95. The main reason for doing this is the increased efficiency and accuracy that occurs when using Horner's scheme to evaluate polynomials. I currently have an implementation of Horner's scheme for univariate/single variable polynomials. However, developing a function to evaluate multivariate polynomials using Horner's scheme is proving to be beyond me. An example bivariate polynomial would be: 12x^2y^2+8x^2y+6xy^2+4xy+2x+2y which would factorised to x(x(y(12y+8))+y(6y+4)+2)+2y and then evaluated for particular values of x & y. Research I've done my research and found a number of papers such as: staff.ustc.edu.cn/~xinmao/ISSAC05/pages/bulletins/articles/147/hornercorrected.pdf citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.40.8637&rep=rep1&type=pdf www.is.titech.ac.jp/~kojima/articles/B-433.pdf Problem However, I'm not a mathematician or computer scientist, so I'm having trouble with the mathematics used to convey the algorithms and ideas. As far as I can tell the basic strategy is to turn a multivariate polynomial into separate univariate polynomials and compute it that way. Can anyone help me? If anyone could help me turn the algorithms into pseudo-code that I can implement into Fortran myself, I would be very grateful.

    Read the article

  • The Math of a Jump in a 2D game.

    - by ONi
    I have been all around with this question and I can't find the correct answer! So, behold, the description of my question: I'm working in J2ME, I have my gameloop that do the following: public void run() { Graphics g = this.getGraphics(); while (running) { long diff = System.currentTimeMillis() - lastLoop; lastLoop = System.currentTimeMillis(); input(); this.level.doLogic(); render(g, diff); try { Thread.sleep(10); } catch (InterruptedException e) { stop(e); } } } so it's just a basic gameloop, the doLogic() function calls for all the logic functions of the characters in the scene and render(g, diff) calls the animateChar function of every character on scene, following this, the animChar function in the Character class sets up everything in the screen as this: protected void animChar(long diff) { this.checkGravity(); this.move((int) ((diff * this.dx) / 1000), (int) ((diff * this.dy) / 1000)); if (this.acumFrame > this.framerate) { this.nextFrame(); this.acumFrame = 0; } else { this.acumFrame += diff; } } This ensures me that everything must to move according to the time that the machine takes to go from cycle to cycle (remember it's a phone, not a gaming rig). I'm sure it's not the most efficient way to achieve this behavior so I'm totally open for criticism of my programming skills in the comments, but here my problem: When I make I character jump, what I do is that I put his dy to a negative value, say -200 and I set the boolean jumping to true, that makes the character go up, and then I have this function called checkGravity() that ensure that everything that goes up has to go down, checkGravity also checks for the character being over platforms so I will strip it down a little for the sake of your time: public void checkGravity() { if (this.jumping) { this.jumpSpeed += 10; if (this.jumpSpeed > 0) { this.jumping = false; this.falling = true; } this.dy = this.jumpSpeed; } if (this.falling) { this.jumpSpeed += 10; if (this.jumpSpeed > 200) this.jumpSpeed = 200; this.dy = this.jumpSpeed; if (this.collidesWithPlatform()) { this.falling = false; this.standing = true; this.jumping = false; this.jumpSpeed = 0; this.dy = this.jumpSpeed; } } } So, the problem is, that this function updates the dy regardless of the diff, making the characters fly like Superman in slow machines, and I have no idea how to implement the diff factor so that when a character is jumping, his speed decrement in a proportional way to the game speed. Can anyone help me fix this issue? or give me pointers on how to make a 2D Jump in J2ME the right way. Thank you very much for your time.

    Read the article

  • jQuery - I'm getting unexpected outputs from a basic math formula.

    - by OllieMcCarthy
    Hi I would like to start by saying I'd greatly appreciate anyones help on this. I have built a small caculator to calculate the amount a consumer can save annually on energy by installing a ground heat pump or solar panels. As far as I can tell the mathematical formulas are correct and my client verified this yesterday when I showed him the code. Two problems. The first is that the calculator is outputting ridiculously large numbers for the first result. The second problem is that the solar result is only working when there are no zeros in the fields. Are there some quirks as to how one would write mathematical formulas in JS or jQuery? Any help greatly appreciated. Here is the link - http://www.olliemccarthy.com/test/johncmurphy/?page_id=249 And here is the code for the entire function - $jq(document).ready(function(){ // Energy Bill Saver // Declare Variables var A = ""; // Input for Oil var B = ""; // Input for Storage Heater var C = ""; // Input for Natural Gas var D = ""; // Input for LPG var E = ""; // Input for Coal var F = ""; // Input for Wood Pellets var G = ""; // Input for Number of Occupants var J = ""; var K = ""; var H = ""; var I = ""; // Declare Constants var a = "0.0816"; // Rate for Oil var b = "0.0963"; // Rate for NightRate var c = "0.0558"; // Rate for Gas var d = "0.1579"; // Rate for LPG var e = "0.121"; // Rate for Coal var f = "0.0828"; // Rate for Pellets var g = "0.02675"; // Rate for Heat Pump var x = "1226.4"; // Splittin up I to avoid error var S1 = ""; // Splitting up the calcuation for I var S2 = ""; // Splitting up the calcuation for I var S3 = ""; // Splitting up the calcuation for I var S4 = ""; // Splitting up the calcuation for I var S5 = ""; // Splitting up the calcuation for I var S6 = ""; // Splitting up the calcuation for I // Calculate H (Ground Sourced Heat Pump) $jq(".es-calculate").click(function(){ $jq(".es-result-wrap").slideDown(300); A = $jq("input.es-oil").val(); B = $jq("input.es-storage").val(); C = $jq("input.es-gas").val(); D = $jq("input.es-lpg").val(); E = $jq("input.es-coal").val(); F = $jq("input.es-pellets").val(); G = $jq("input.es-occupants").val(); J = ( A / a ) + ( B / b ) + ( C / c ) + ( D / d ) + ( E / e ) + ( F / f ) ; H = A + B + C + D + E + F - ( J * g ) ; K = ( G * x ) ; if ( A !== "0" ) { S1 = ( ( ( A / a ) / J ) * K * a ) ; } else { S1 = "0" ; } if ( B !== "0" ) { S2 = ( ( ( B / b ) / J ) * K * b ) ; } else { S2 = "0" ; } if ( C !== "0" ) { S3 = ( ( ( C / c ) / J ) * K * c ) ; } else { S3 = "0" ; } if ( D !== "0" ) { S4 = ( ( ( D / d ) / J ) * K * d ) ; } else { S4 = "0" ; } if ( E !== "0" ) { S5 = ( ( ( E / e ) / J ) * K * e ) ; } else { S5 = "0" ; } if ( F !== "0" ) { S6 = ( ( ( F / f ) / J ) * K * f ) ; } else { S6 = "0" ; } I = S1 + S2 + S3 + S4 + S5 + S6 ; if(!isNaN(H)) {$jq("span.es-result-span-h").text(H.toFixed(2));} else{$jq("span.es-result-span-h").text('Error: Please enter numerals only');} if(!isNaN(I)) {$jq("span.es-result-span-i").text(I.toFixed(2));} else{$jq("span.es-result-span-i").text('Error: Please enter numerals only');} }); });

    Read the article

  • How do I get the Math equation of Python Algorithm?

    - by Gabriel
    ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x 0 add all numbers together from 1 to x. def fac(x): if x > 0: return x + fac(x - 1) else: return 0 fac(10) 55 first what is this type of equation is this and what is the correct way to get this answer as it is clearly easier using some other method?

    Read the article

  • What is the best practice when coding math class/functions ?

    - by Isaac Clarke
    Introductory note : I voluntarily chose a wide subject. You know that quote about learning a cat to fish, that's it. I don't need an answer to my question, I need an explanation and advice. I know you guys are good at this ;) Hi guys, I'm currently implementing some algorithms into an existing program. Long story short, I created a new class, "Adder". An Adder is a member of another class representing the physical object actually doing the calculus , which calls adder.calc() with its parameters (merely a list of objects to do the maths on). To do these maths, I need some parameters, which do not exist outside of the class (but can be set, see below). They're neither config parameters nor members of other classes. These parameters are D1 and D2, distances, and three arrays of fixed size : alpha, beta, delta. I know some of you are more comfortable reading code than reading text so here you go : class Adder { public: Adder(); virtual Adder::~Adder(); void set( float d1, float d2 ); void set( float d1, float d2, int alpha[N_MAX], int beta[N_MAX], int delta[N_MAX] ); // Snipped prototypes float calc( List& ... ); // ... inline float get_d1() { return d1_ ;}; inline float get_d2() { return d2_ ;}; private: float d1_; float d2_; int alpha_[N_MAX]; // A #define N_MAX is done elsewhere int beta_[N_MAX]; int delta_[N_MAX]; }; Since this object is used as a member of another class, it is declared in a *.h : private: Adder adder_; By doing that, I couldn't initialize the arrays (alpha/beta/delta) directly in the constructor ( int T[3] = { 1, 2, 3 }; ), without having to iterate throughout the three arrays. I thought of putting them in static const, but I don't think that's the proper way of solving such problems. My second guess was to use the constructor to initialize the arrays Adder::Adder() { int alpha[N_MAX] = { 0, -60, -120, 180, 120, 60 }; int beta[N_MAX] = { 0, 0, 0, 0, 0, 0 }; int delta[N_MAX] = { 0, 0, 180, 180, 180, 0 }; set( 2.5, 0, alpha, beta, delta ); } void Adder::set( float d1, float d2 ) { if (d1 > 0) d1_ = d1; if (d2 > 0) d2_ = d2; } void Adder::set( float d1, float d2, int alpha[N_MAX], int beta[N_MAX], int delta[N_MAX] ) { set( d1, d2 ); for (int i = 0; i < N_MAX; ++i) { alpha_[i] = alpha[i]; beta_[i] = beta[i]; delta_[i] = delta[i]; } } My question is : Would it be better to use another function - init() - which would initialize arrays ? Or is there a better way of doing that ? My bonus question is : Did you see some mistakes or bad practice along the way ?

    Read the article

  • MySQL Math - Is it possible to calculate a correlation in a query?

    - by John M
    In a MySQL (5.1) database table there is data that represents: how long a user takes to perform a task and how many items the user handled during the task. Would MySQL support correlating the data or do I need to use PHP/C# to calcuate? Where would I find a good formula to calculate correlation (it's been a long time since I last did this)?

    Read the article

  • Complicated programming and math tasks online. Any?

    - by Tom
    Maybe it is not very thematic question in here, but I guess it will be interesting not only to me. I hope. So, I just want to get some cool tasks to do using programming languages or just pen and sheet of paper. I guess it can lead to improving my ability to do better code (more optimal I mean.) Do you know any websites where I can find it? Thanks.

    Read the article

  • Math - Convert Arbitrary Length to Range From -1.0 to 1.0?

    - by TheDarkIn1978
    how can i convert a length into a range of -1.0 to 1.0? example: my stage is 440px in length and accepts mouse events. i would like to click in the middle of the stage, and rather than an output of X = 220, i'd like it to be X = 0. similarly, i'd like the real X = 0 to become X = -1.0 and the real X = 440 to become X = 1.0. i don't have access to the stage, so i can't simply center-register it, which would make this process a lot easier. also, it's not possible to dynamically change the actual size of my stage, so i'm looking for a formula that will translate the mouse's real X coordinate of the stage to evenly fit within a range from -1 to 1.

    Read the article

  • Silverlight - round doubles away from zero

    - by Cornel
    In Silverlight the Math.Round() method does not contain an overload with 'MidpointRounding' parameter. What is the best approach to round a double away from zero in Silverlight in this case? Example: Math.Round(1.4) = 1 Math.Round(1.5) = 2 Math.Round(1.6) = 2

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >