Search Results

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

Page 122/137 | < Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >

  • Refresh Div with Jquery at fixed time

    - by Ben C
    I've got a php script that tells me when the next bus is due, and at the moment I'm refreshing this into a div, using jquery, every minute or so. Now, because I know the time at which the data will change (after the bus has come), I want it to refresh the div at this time (or just after, doesn't really matter). I should point out that I'm fairly new to js, but this is what I've got so far: var nextbustime = $('#bus').contents(); var nextbustime = new Date(nextbustime); var now = new Date(); var t = nextbustime.getTime() - now.getTime(); var refreshId = setTimeout(function() { $('#bus').fadeOut("slow").load('modules/bus.php?randval='+ Math.random()).fadeIn("slow"); }, t); The div is loaded originally with a php include. Naturally, what I've done doesn't work at all. Do I need some loops going on? Do I need to refresh the time calculator? Please please help! Thanks in advance...

    Read the article

  • Attempt to use a while loop for the 'next' arg of a for loop generates #arg error

    - by JerryK
    Am attempting to teach myself to program using Tcl. The task i've set myself to motivate my learning of Tcl is to solve the 8 queens problem. My approach to creating a program is to successively 'prototype' a solution. I have asked an earlier question related to the correctly laying out the nested for loops and received a helpful answer. To my dismay I find that the next development of my code creates the same interpreter error : "wrong # args" I have been careful to have an open brace at the end of the line preceding the while loop command. I've also tried to put the arguments of the whileloop in braces. This generates a different error. I have sincerely tried to understand the Tcl syntax man page - not too successfully - suggested by the answerer of my earlier question. Here is the code set allowd 1 set notallowd 0 for {set r1p 1} {$r1p <= 8} {incr r1p } { puts "1st row q placed at $r1p" ;# re-initialize r2 'free for q placemnt' array after every change of r1 q pos: for {set i 1 } {$i <= 8} {incr i} { set r2($i) $allowd } for { set r2($r1p) $notallowd ; set r2([expr $r1p-1]) $notallowd ; set r2([expr $r1p+1]) $notallowd ; set r2p 1} {$r2p <= 8} { ;# 'next' arg of r2 forloop will be a whileloop : while r2($r2p)== $notallowd incr r2p } { puts "2nd row q placed at $r2p" ;# end of 'commnd' arg of r2 forloop } } Where am I going wrong? EDIT : to provide clear reply @slebetman As stated in my text, I did brace the arguments of the whileloop (indeed that was how i first wrote the code) below is exactly the layout of the r2 forloop tried: for { set r2($r1p) $notallowd ; set r2([expr $r1p-1]) $notallowd ; set r2([expr $r1p+1]) $notallowd ; set r2p 1} {$r2p <= 8} { ;# 'next' arg of r2 forloop will be a whileloop : while { r2($r2p)== $notallowd } { incr r2p } } { puts "2nd row q placed at $r2p" ;# end of 'commnd' arg of r2 forloop } but this generates the fatal interpreter error : "unknown math function 'r2' while compiling while { r2($r2p .... "

    Read the article

  • Time complexity of a powerset generating function

    - by Lirik
    I'm trying to figure out the time complexity of a function that I wrote (it generates a power set for a given string): public static HashSet<string> GeneratePowerSet(string input) { HashSet<string> powerSet = new HashSet<string>(); if (string.IsNullOrEmpty(input)) return powerSet; int powSetSize = (int)Math.Pow(2.0, (double)input.Length); // Start at 1 to skip the empty string case for (int i = 1; i < powSetSize; i++) { string str = Convert.ToString(i, 2); string pset = str; for (int k = str.Length; k < input.Length; k++) { pset = "0" + pset; } string set = string.Empty; for (int j = 0; j < pset.Length; j++) { if (pset[j] == '1') { set = string.Concat(set, input[j].ToString()); } } powerSet.Add(set); } return powerSet; } So my attempt is this: let the size of the input string be n in the outer for loop, must iterate 2^n times (because the set size is 2^n). in the inner for loop, we must iterate 2*n times (at worst). 1. So Big-O would be O((2^n)*n) (since we drop the constant 2)... is that correct? And n*(2^n) is worse than n^2. if n = 4 then (4*(2^4)) = 64 (4^2) = 16 if n = 100 then (10*(2^10)) = 10240 (10^2) = 100 2. Is there a faster way to generate a power set, or is this about optimal?

    Read the article

  • Detect mouseover and show tooltip text for dots on an HTML Canvas

    - by carl asquith
    Ive recently created a "map" although not very sophisticated (im working on it) it has the basic function and is generally heading in the right direction. If you look at it you can see a tiny red dots and on those tiny red dots i want to mouseover it and see text basically but ive had a bit of trouble getting the code right. http://hummingbird2.x10.mx/website%20creation/mainpage.htm This is all the code so far. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Oynx Warrior</title> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> <body> <h1>Oynx Warrior</h1> <canvas id="myCanvas" width="500" height="500" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); cxt.fillStyle="#red"; cxt.beginPath(); cxt.arc(50,50,1,0,Math.PI*2,true); cxt.closePath(); cxt.fill(); </script> </body> </html>

    Read the article

  • C program - Seg fault, cause of

    - by resonant_fractal
    Running this gives me a seg fault (gcc filename.c -lm), when i enter 6 (int) as a value. Please help me get my head around this. The intended functionality has not yet been implemented, but I need to know why I'm headed into seg faults already. Thanks! #include<stdio.h> #include<math.h> int main (void) { int l = 5; int n, i, tmp, index; char * s[] = {"Sheldon", "Leonard", "Penny", "Raj", "Howard"}; scanf("%d", &n); //Solve Sigma(Ai*2^(i-1)) = (n - k)/l if (n/l <= 1) printf("%s\n", s[n-1]); else { tmp = n; for (i = 1;;) { tmp = tmp - (l * pow(2,i-1)); if (tmp <= 5) { // printf("Breaking\n"); break; } ++i; } printf("Last index = %d\n", i); // ***NOTE*** //Value lies in next array, therefore ++i; index = tmp + pow(2, n-1); printf("%d\n", index); } return 0; }

    Read the article

  • Drawing line graphics leads Flash to spiral out of control!

    - by drpepper
    Hi, I'm having problems with some AS3 code that simply draws on a Sprite's Graphics object. The drawing happens as part of a larger procedure called on every ENTER_FRAME event of the stage. Flash neither crashes nor returns an error. Instead, it starts running at 100% CPU and grabs all the memory that it can, until I kill the process manually or my computer buckles under the pressure when it gets up to around 2-3 GB. This will happen at a random time, and without any noticiple slowdown beforehand. WTF? Has anyone seen anything like this? PS: I used to do the drawing within a MOUSE_MOVE event handler, which brought this problem on even faster. PPS: I'm developing on Linux, but reproduced the same problem on Windows. UPDATE: You asked for some code, so here we are. The drawing function looks like this: public static function drawDashedLine(i_graphics : Graphics, i_from : Point, i_to : Point, i_on : Number, i_off : Number) : void { const vecLength : Number = Point.distance(i_from, i_to); i_graphics.moveTo(i_from.x, i_from.y); var dist : Number = 0; var lineIsOn : Boolean = true; while(dist < vecLength) { dist = Math.min(vecLength, dist + (lineIsOn ? i_on : i_off)); const p : Point = Point.interpolate(i_from, i_to, 1 - dist / vecLength); if(lineIsOn) i_graphics.lineTo(p.x, p.y); else i_graphics.moveTo(p.x, p.y); lineIsOn = !lineIsOn; } } and is called like this (m_graphicsLayer is a Sprite): m_graphicsLayer.graphics.clear(); if (m_destinationPoint) { m_graphicsLayer.graphics.lineStyle(2, m_fixedAim ? 0xff0000 : 0x333333, 1); drawDashedLine(m_graphicsLayer.graphics, m_initialPos, m_destinationPoint, 10, 10); }

    Read the article

  • Sorting in Lua, counting number of items

    - by Josh
    Two quick questions (I hope...) with the following code. The script below checks if a number is prime, and if not, returns all the factors for that number, otherwise it just returns that the number prime. Pay no attention to the zs. stuff in the script, for that is client specific and has no bearing on script functionality. The script itself works almost wonderfully, except for two minor details - the first being the factor list doesn't return itself sorted... that is, for 24, it'd return 1, 2, 12, 3, 8, 4, 6, and 24 instead of 1, 2, 3, 4, 6, 8, 12, and 24. I can't print it as a table, so it does need to be returned as a list. If it has to be sorted as a table first THEN turned into a list, I can deal with that. All that matters is the end result being the list. The other detail is that I need to check if there are only two numbers in the list or more. If there are only two numbers, it's a prime (1 and the number). The current way I have it does not work. Is there a way to accomplish this? I appreciate all the help! function get_all_factors(number) local factors = 1 for possible_factor=2, math.sqrt(number), 1 do local remainder = number%possible_factor if remainder == 0 then local factor, factor_pair = possible_factor, number/possible_factor factors = factors .. ", " .. factor if factor ~= factor_pair then factors = factors .. ", " .. factor_pair end end end factors = factors .. ", and " .. number return factors end local allfactors = get_all_factors(zs.param(1)) if zs.func.numitems(allfactors)==2 then return zs.param(1) .. " is prime." else return zs.param(1) .. " is not prime, and its factors are: " .. allfactors end

    Read the article

  • Attempted GCF app for Android

    - by Aaron
    I am new to Android and am trying to create a very basic app that calculates and displays the GCF of two numbers entered by the user. Here is a copy of my GCF.java: package com.example.GCF; import java.util.Arrays; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class GCF extends Activity { private TextView mAnswer; private EditText mA, mB; private Button ok; private String A, B; private int iA, iB; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mA = (EditText) findViewById(R.id.entry); mB = (EditText) findViewById(R.id.entry1); ok = (Button) findViewById(R.id.ok); mAnswer = (TextView) findViewById(R.id.answer1); ok.setOnClickListener(new OnClickListener() { public void onClick(View v) { A = mA.getText().toString(); B = mB.getText().toString(); } }); // the String to int conversion happens here iA = Integer.parseInt(A.trim()); iB = Integer.parseInt(B.trim()); while (iA != iB) { int[] nums={ iA, iB, Math.abs(iA-iB) }; Arrays.sort(nums); iA=nums[0]; iB=nums[1]; } updateDisplay(); } private void updateDisplay() { mAnswer.setText( new StringBuilder().append(iA)); } } Any Suggestions? Thank you!

    Read the article

  • F# How to tokenise user input: separating numbers, units, words?

    - by David White
    I am fairly new to F#, but have spent the last few weeks reading reference materials. I wish to process a user-supplied input string, identifying and separating the constituent elements. For example, for this input: XYZ Hotel: 6 nights at 220EUR / night plus 17.5% tax the output should resemble something like a list of tuples: [ ("XYZ", Word); ("Hotel:", Word); ("6", Number); ("nights", Word); ("at", Operator); ("220", Number); ("EUR", CurrencyCode); ("/", Operator); ("night", Word); ("plus", Operator); ("17.5", Number); ("%", PerCent); ("tax", Word) ] Since I'm dealing with user input, it could be anything. Thus, expecting users to comply with a grammar is out of the question. I want to identify the numbers (could be integers, floats, negative...), the units of measure (optional, but could include SI or Imperial physical units, currency codes, counts such as "night/s" in my example), mathematical operators (as math symbols or as words including "at" "per", "of", "discount", etc), and all other words. I have the impression that I should use active pattern matching -- is that correct? -- but I'm not exactly sure how to start. Any pointers to appropriate reference material or similar examples would be great.

    Read the article

  • Int - number too large. How to get program to fail?

    - by Dave
    Hi Problem: How do you get a program to fail if a number goes beyond the bounds of its type? This code below gives the wrong answer for sum of primes under 2 million as I'd used an int instead of a long. [TestMethod] public void CalculateTheSumOfPrimesBelow2million() { int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million Assert.AreEqual(1, result); // 1,179,908,154 .. this was what I got with an int... // correct answer was 142,913,828,922 with a long } public static class PrimeTester { public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow) { // we know 2 is a prime number int sumOfPrimes = 2; int currentNumberBeingTested = 3; while (currentNumberBeingTested < maxPrimeBelow) { double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested); bool isPrime = true; for (int i = 2; i <= squareRootOfNumberBeingTested; i++) { if (currentNumberBeingTested % i == 0) { isPrime = false; break; } } if (isPrime) sumOfPrimes += currentNumberBeingTested; currentNumberBeingTested += 2; // as we don't want to test even numbers } return sumOfPrimes; } }

    Read the article

  • returning a pointed to an object within a std::vector

    - by memC
    I have a very basic question on returning a reference to an element of a vector . There is a vector vec that stores instances of class Foo. I want to access an element from this vector . ( don't want to use the vector index) . How should I code the method getFoo here? #include<vector> #include<stdio.h> #include<iostream> #include<math.h> using namespace std; class Foo { public: Foo(){}; ~Foo(){}; }; class B { public: vector<Foo> vec; Foo* getFoo(); B(){}; ~B(){}; }; Foo* B::getFoo(){ int i; vec.push_back(Foo()); i = vec.size() - 1; // how to return a pointer to vec[i] ?? return vec.at(i); }; int main(){ B b; b = B(); int i = 0; for (i = 0; i < 5; i ++){ b.getFoo(); } return 0; }

    Read the article

  • How would you update 100+ variables if something is changed in a different class?

    - by N. Lucas
    I have a class Grid which produces a graph paper like grid on in the drawing area. I then have 5 other classes for different shapes to draw with; Line, Polygon, Ellipse, Curve, Arc Now, these 5 classes use an instance of Grid because Grid has a resolution and a scale. Inside Grid I have: public function set resolution(x:Number):void { _gap = (modBy10(x) / 10); _scale = (modBy10(x) / (this.resolution * _scale)); draw(); } public function get resolution():Number { return (_gap * 10); } public function set scale(x:Number):void { _scale = (this.resolution / x); } public function get scale():Number { return _scale; } /**/ public function scaleLength(x:Number):Number { return (x * this.scale); } public function scaleLengthDown(x:Number):Number { return (x / this.scale); } public function scaleArea(x:Number):Number { return (x / Math.pow(this.scale, 2)); } I'm just lost for a solution on how to update every instance of my 5 drawing classes when Grid is changed. For instance, Polygon is made up of multiple instances of Line, Line(length, angle) where "length" is in either in, ft, cm, or m. If the user wishes to change the scale from say 10ft per 100px resolution.. Is there an easier way than re-drawing every Line inside Polygon?

    Read the article

  • How to display buttons after enterframe event is over in Corona?

    - by user1463542
    I am trying to display two buttons called countd_again and main_menu after my enterframe event is over. I can't see those buttons after enterframe event is over,though. Can you check my code,please? And also i want to add new addListener for the buttons using director and scene. module(..., package.seeall) function new() local localGroup = display.newGroup(); display.setStatusBar(display.HiddenStatusBar) local background = display.newImage("background.png") start=os.time() cnt=1 local countd_again = display.newImage("yeniden.png") countd_again.x=100 countd_again.y=100 countd_again.isVisible= false; countd_again.alpha=0; countd_again.scene="helloWorld"; local main_menu= display.newImage("anamenu.png") main_menu.x=100 main_menu.y=300 main_menu.isVisible=false; main_menu.alpha=0; main_menu.scene="helloWorld" -- listener function local function onEveryFrame( event ) if (cnt~=0) then cnt= 3-(os.time()-start) minute = math.floor(cnt/60) second=cnt%60 --print(minute,second) minTxt=display.newText(minute,50,50,nil,100) secTxt=display.newText(second,250,50,nil,100) transition.to(minTxt, {time=100, alpha=0}) transition.to(secTxt,{time=100, alpha=0}) else Runtime: removeEventListener("enterFrame",onEveryFrame) countd_again.isVisible=true; main_menu.isVisible=true; transition.to(countd_again,{time=500,alpha=1}); transition.to(main_menu,{time=500,alpha=1}); countd_again: addEventListener("touch", changeScene) main_menu: addEventListener("touch", changeScene) end end -- assign the above function as an "enterFrame" listener Runtime:addEventListener( "enterFrame", onEveryFrame ) function changeScene(e) if(e.phase=="ended") then director:changeScene(e.target.scene); end end countd_again: addEventListener("touch", changeScene) main_menu: addEventListener("touch", changeScene) localGroup: insert(countd_again) localGroup:insert(main_menu) localGroup:insert(background) return localGroup; end

    Read the article

  • WPF Drag-to-scroll doesn't work correctly.

    - by Garegin
    Hi all, I am tying to realize a drag-to-scroll functionality in my application and have problems on my way. Can anybody help me? I have a ScrollViewer and inside it an ItemsControl and within ItemsTemplate I have a UserControl. I want to drag that UserControl within ItemsControl. I want the ScrollViewer to scroll down, when I am dragging to the boundaries of the ItemsControl. protected override void OnPreviewMouseMove(System.Windows.Input.MouseEventArgs e) { if (this.IsMouseCaptured) { // Get the new mouse position. Point mouseDragCurrentPoint = e.GetPosition(this); if (Math.Abs(mouseDragCurrentPoint.Y - this.ActualHeight) <= 50) { this._scrollStartOffset.Y += 5; _containingScrollViewer.ScrollToVerticalOffset(this._scrollStartOffset.Y); } if (mouseDragCurrentPoint.Y <= 50) { this._scrollStartOffset.Y -= 5; _containingScrollViewer.ScrollToVerticalOffset(this._scrollStartOffset.Y); } } base.OnPreviewMouseMove(e); } When i start dragging by calling DragDrop.DoDragDrop() scrolling don't happens. But when i disable dragging, the ScrollViewer scrolls down dependong on mouse position. Maybe there's something that i don't take into accont about dragging and Capturing the mouse? Thanks for attention. Garegin

    Read the article

  • Reading input files in FORTRAN

    - by lollygagger
    Purpose: Create a program that takes two separate files, opens and reads them, assigns their contents to arrays, do some math with those arrays, create a new array with product numbers, print to a new file. Simple enough right? My input files have comment characters at the beginning. One trouble is, they are '#' which are comment characters for most plotting programs, but not FORTRAN. What is a simple way to tell the computer not to look at these characters? Since I have no previous FORTRAN experience, I am plowing through this with two test files. Here is what I have so far: PROGRAM gain IMPLICIT NONE REAL, DIMENSION (1:4, 1:8) :: X, Y, Z OPEN(1, FILE='test.out', & STATUS='OLD', ACTION='READ') ! opens the first file READ(1,*), X OPEN(2, FILE='test2.out', & STATUS='OLD', ACTION='READ') ! opens the second file READ(2,*), Y PRINT*, X, Y Z = X*Y ! PRINT*, Z OPEN(3, FILE='test3.out', STATUS='NEW', ACTION='WRITE') !creates a new file WRITE(3,*), Z CLOSE(1) CLOSE(2) CLOSE(3) END PROGRAM PS. Please do not overwhelm me with a bunch of code monkey gobblety gook. I am a total programming novice. I do not understand all the lingo, that is why I came here instead of searching for help in existing websites. Thanks.

    Read the article

  • graph and all pairs shortest path in java

    - by Sandra
    I am writing a java program using Flyod-Warshall algorithm “All pairs shortest path”. I have written the following : a0 is the adjacency matrix of my graph, but has infinity instead of 0. vList is the list of vertexes and the cost for each edge is 1. Path[i][j] = k+1 means for going from I to j you first go to k then j int[][] path = new int[size][size]; for(int i = 0; i<path.length;i++) { for(int j = 0; j<path.length; j++) { if(adjM[i][j]==1) path[i][j]=j+1; } } //*************** for (int k = 0; k < vList.size(); k++) for (int i = 0; i < vList.size(); i++) for (int j = 0; j < vList.size(); j++) { if (a0[i][j]>a0[i][k]+ a0[k][j]) path[i][j] = k + 1; a0[i][j] = Math.min(a0[i][j], a0[i][k] + a0[k][j]); } After running this code, in the result a0 is correct, but path is not correct and I don’t know why!. Would you please help me?

    Read the article

  • How to break out from nested doseqs

    - by fizbin
    Hi, I have a question regarding nested doseq loops. In the start function, once I find an answer I set the atom to true, so that the outer loop validation with :while fails. However it seems that it doesn't break it, and the loops keep on going. What's wrong with it? I am also quite confused with the usage of atoms, refs, agents (Why do they have different names for the update functions when then the mechanism is almost the same?) etc. Is it okay to use an atom in this situation as a flag? Obviously I need a a variable like object to store a state. (def pentagonal-list (map (fn [a] (/ (* a (dec (* 3 a))) 2)) (iterate inc 1))) (def found (atom false)) (defn pentagonal? [a] (let [y (/ (inc (Math/sqrt (inc (* 24 a)))) 6) x (mod (* 10 y) 10)] (if (zero? x) true false))) (defn both-pent? [a b] (let [sum (+ b a) diff (- a b)] (if (and (pentagonal? sum) (pentagonal? diff)) true false))) (defn start [] (doseq [x pentagonal-list :while (false? @found)] (doseq [y pentagonal-list :while (<= y x)] (if (both-pent? x y) (do (reset! found true) (println (- x y)))))))

    Read the article

  • loop is cut one element of the array

    - by Walaa
    The problem is : Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents. My code : import java.util.*; public class Q1 { static Scanner scan = new Scanner (System.in); public static void main(String args [] ) { int num; int i = 0; System.out.println("Enter a number :"); num = scan.nextInt(); double [] a=new double[num]; a[0]= num ; for ( ;i<=a.length-1 ; i++) { a[i+1] = Math.pow(2,a[i]); System.out.println((int)(a[i]) ); } } } The error is : ----jGRASP exec: java Q1 Enter a number : 4 4 16 65536 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Q1.main(Q1.java:16) ----jGRASP wedge2: exit code for process is 1. why it says that? And the number by user printed twice!

    Read the article

  • Cannot make a static reference to the non-static type MyRunnable

    - by kaiwii ho
    Here is the whole code : import java.util.ArrayList; public class Test{ ThreadLocal<ArrayList<E>>arraylist=new ThreadLocal<ArrayList<E>>(){ @Override protected ArrayList<E> initialValue() { // TODO Auto-generated method stub //return super.initialValue(); ArrayList<E>arraylist=new ArrayList<E>(); for(int i=0;i<=20;i++) arraylist.add((E) new Integer(i)); return arraylist; } }; class MyRunnable implements Runnable{ private Test mytest; public MyRunnable(Test test){ mytest=test; // TODO Auto-generated constructor stub } @Override public void run() { System.out.println("before"+mytest.arraylist.toString()); ArrayList<E>myarraylist=(ArrayList<E>) mytest.arraylist.get(); myarraylist.add((E) new Double(Math.random())); mytest.arraylist.set(myarraylist); System.out.println("after"+mytest.arraylist.toString()); } // TODO Auto-generated method stub } public static void main(String[] args){ Test test=new Test<Double>(); System.out.println(test.arraylist.toString()); new Thread(new MyRunnable(test)).start(); new Thread(new MyRunnable(test)).start(); System.out.println(arraylist.toString()); } } my questions are: 1\ why the new Thread(new MyRunnable(test)).start(); cause the error: Cannot make a static reference to the non-static type MyRunnable ? 2\ what is the static reference refer to right here? thx in advanced

    Read the article

  • Using "from __future__ import division" in my program, but it isn't loaded with my program

    - by Sara Fauzia
    I wrote the following program in Python 2 to do Newton's method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with %run -i NewtonsMethodMultivariate.py, the Python 3 division is not imported. I know this because after I load my Python program, entering x**(3/4) gives "1". After manually importing the new division, then x**(3/4) remains x**(3/4), as expected. Why is this? # coding: utf-8 from __future__ import division from sympy import symbols, Matrix, zeros x, y = symbols('x y') X = Matrix([[x],[y]]) tol = 1e-3 def roots(h,a): def F(s): return h.subs({x: s[0,0], y: s[1,0]}) def D(s): return h.jacobian(X).subs({x: s[0,0], y: s[1,0]}) if F(a) == zeros(2)[:,0]: return a else: while (F(a)).norm() > tol: a = a - ((D(a))**(-1))*F(a) print a.evalf(10) I would use Python 3 to avoid this issue, but my Linux distribution only ships SymPy for Python 2. Thanks to the help anyone can provide. Also, in case anyone was wondering, I haven't yet generalized this script for nxn Jacobians, and only had to deal with 2x2 in my problem set. Additionally, I'm slicing the 2x2 zero matrix instead of using the command zeros(2,1) because SymPy 0.7.1, installed on my machine, complains that "zeros() takes exactly one argument", though the wiki suggests otherwise. Maybe this command is only for the git version.

    Read the article

  • My method is too specific. How can I make it more generic?

    - by EricBoersma
    I have a class, the outline of which is basically listed below. import org.apache.commons.math.stat.Frequency; public class WebUsageLog { private Collection<LogLine> logLines; private Collection<Date> dates; WebUsageLog() { this.logLines = new ArrayList<LogLine>(); this.dates = new ArrayList<Date>(); } SortedMap<Double, String> getFrequencyOfVisitedSites() { SortedMap<Double, String> frequencyMap = new TreeMap<Double, String>(Collections.reverseOrder()); //we reverse order to sort from the highest percentage to the lowest. Collection<String> domains = new HashSet<String>(); Frequency freq = new Frequency(); for (LogLine line : this.logLines) { freq.addValue(line.getVisitedDomain()); domains.add(line.getVisitedDomain()); } for (String domain : domains) { frequencyMap.put(freq.getPct(domain), domain); } return frequencyMap; } } The intention of this application is to allow our Human Resources folks to be able to view Web Usage Logs we send to them. However, I'm sure that over time, I'd like to be able to offer the option to view not only the frequency of visited sites, but also other members of LogLine (things like the frequency of assigned categories, accessed types [text/html, img/jpeg, etc...] filter verdicts, and so on). Ideally, I'd like to avoid writing individual methods for compilation of data for each of those types, and they could each end up looking nearly identical to the getFrequencyOfVisitedSites() method. So, my question is twofold: first, can you see anywhere where this method should be improved, from a mechanical standpoint? And secondly, how would you make this method more generic, so that it might be able to handle an arbitrary set of data?

    Read the article

  • [C++] Trouble declaring and recognizing global functions

    - by Sarah
    I've created some mathematical functions that will be used in main() and by member functions in multiple host classes. I was thinking it would be easiest to make these math functions global in scope, but I'm not sure how to do this. I've currently put all the functions in a file called Rdraws.cpp, with the prototypes in Rdraws.h. Even with all the #includes and externs, I'm getting a "symbol not found" error at the first function call in main(). Here's what I have: // Rdraws.cpp #include <cstdlib> using namespace std; #include <cmath> #include "Rdraws.h" #include "rng.h" extern RNG rgen // this is the PRNG used in the simulation; global scope void rmultinom( double p_trans[], int numTrials, int numTrans, int numEachTrans[] ) { // function 1 def } void rmultinom( const double p_trans[], const int numTrials, int numTrans, int numEachTrans[]) { // function 2 def } int rbinom( int nTrials, double pLeaving ) { // function 3 def } // Rdraws.h #ifndef RDRAWS #define RDRAWS void rmultinom( double[], int, int, int[] ); void rmultinom( const double[], const int, int, int[] ); int rbinom( int, double ); #endif // main.cpp ... #include "Rdraws.h" ... extern void rmultinom(double p_trans[], int numTrials, int numTrans, int numEachTrans[]); extern void rmultinom(const double p_trans[], const int numTrials, int numTrans, int numEachTrans[]); extern int rbinom( int n, double p ); ... int main() { ... } I'm pretty new to programming. If there's a dramatically smarter way to do this, I'd love to know.

    Read the article

  • jQuery .height() property not working

    - by Andrew
    I'm attempting to get the height of an element using jQuery, but am receiving some unexpected results. Here's the code: $(function() { var contentheight = $('#subpage-content-small').height; alert(contentheight); }); Where #subpage-content-small has these CSS properties: #subpage-content-small { width: 400px; float: left; margin: 30px 10px 0 0; padding-bottom: 45px; } What I'm getting as an output for my alert is the following: function (f) { var e = this[0]; if (!e) { return f == null ? null : this; } if (c.isFunction(f)) { return this.each(function (j) {var i = c(this);i[d](f.call(this, j, i[d]()));}); } return "scrollTo" in e && e.document ? e.document.compatMode === "CSS1Compat" && e.document.documentElement["client" + b] || e.document.body["client" + b] : e.nodeType === 9 ? Math.max(e.documentElement["client" + b], e.body["scroll" + b], e.documentElement["scroll" + b], e.body["offset" + b], e.documentElement["offset" + b]) : f === w ? c.css(e, d) : this.css(d, typeof f === "string" ? f : f + "px"); } Any idea why I'm getting this as opposed to an integer of the height? Thanks in advance!

    Read the article

  • Looking for an appropriate design pattern

    - by user1066015
    I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version): Class Player{ int id; public Player(){ int id = Math.random()*100000; PlayerData.players.put(id,new PlayerData()); } public void jump(){ //Logic to make the user jump //... //call the playerManager PlayerManager.jump(this); } public void attack(Player target){ //logic to attack the player //... //call the player manager PlayerManager.attack(this,target); } } Class PlayerData{ public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>(); int id; int timesJumped; int timesAttacked; } public void incrementJumped(){ timesJumped++; } public void incrementAttacked(){ timesAttacked++; } } Class PlayerManager{ public static void jump(Player player){ players.get(player.getId()).incrementJumped(); } public void incrementAttacked(Player player, Player target){ players.get(player.getId()).incrementAttacked(); } } So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits". The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized. If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.

    Read the article

  • HLSL - Combining textures

    - by b34r
    Hi All, I'm trying to combine two textures in HLSL - specifically, I want to take the alpha values from a base image, and the color data from an overlay image. My pixel shader for this looks like this: float4 PixelShaderFunction(VertexOut input) : COLOR0 { float4 baseColor = tex2D( BaseSampler, input.baseCoords.xy ).rgba; float4 overlayColor = tex2D( OverlaySampler, input.overlayCoords.xy ).rgba; float4 color; color.r = overlayColor.r; color.g = overlayColor.g; color.b = overlayColor.b; color.a = baseColor.a; return color.rgba; } and my blend state looks like this: BlendState bs = new BlendState(); bs.AlphaSourceBlend = Blend.SourceAlpha; bs.AlphaDestinationBlend = Blend.DestinationAlpha; bs.ColorSourceBlend = Blend.SourceColor; bs.ColorDestinationBlend = Blend.DestinationColor; What this leaves me with is a washed out version of what should be the overlay color. I've tried numerous permutations of the BlendState settings, and played with the pixel shader math quite a bit, but to no avail. Can anyone point me in the right direction? Thanks in advance =)

    Read the article

< Previous Page | 118 119 120 121 122 123 124 125 126 127 128 129  | Next Page >