# RandomBystander

Member

16

122 Neutral

• Rank
Member
1. ## Virtual function design question

Quote:Original post by Zahlman Quote:Original post by SimonFarris The new class that I'm trying to add(I) is an item type where the price depends on the time of day or the day of the week. So the first question you need to find the answer to is: why does the price of I depend on time, when the price of nothing else does? (Not being the OP, nor a learned economist, I try to answer anyway.) Because buyer and seller have agreed that it does. In other words, it doesn't. It does not explicitly depend on time, that is. Explicitly, it only depends on the buyer and the seller, who negotiate the price. This negitiation always happens, even at the supermarket. The price label communicates an offer to sell the good at the stated price in household quantities, while there is any in stock, until further notice, and by carrying it to the cashier, you communicate that you agree to the terms. Implicitly, however, there might be a sign saying that fruit and vegetables are half price after saturday noon. Of course, the number on the price label does not depend on the customer, only the seller and his estimation of the market. Short version: You do not ask the good itself about its price. Instead you look at the price label or, if there is none, ask the merchand selling it (which usually amounts to the same thing).
2. ## Virtual function design question

While waiting for more context... Basically, class I needs some extra information via class X to fulfill the promise given by A::func(). Instead of pushing this information, let class I simply pull it. class X { private: static X* last_created; public: static X* get_last_created() { if (last_created==0) throw PleasePanicNow("HAND"); return last_created; } X() { last_created=this;} ~X() { if (last_created==this) last_created=0;} }; class I { public: int func() { X* x=X::get_last_created(); // do something } }; void somefunc() { X x; for ( i=0; i<avector.size( );i++ ) { A* a=avector; int result=a->func(); /* mysterious stuff happens */ } } As far as I can see, this code has the same behaviour as yours - unless the constructor of X is called at an inopportune moment.
3. ## (c++) warning when local variable is overriden by another local variable

Quote:Original post by samothGcc certainly does too, it tells you something like "suggest placing {} around empty statement". So basically you have to write if(blah){ ; } Gcc with -Wall does not, but -Wextra enables this warning for if, while, for and do-while.
4. ## Enumeration vs #define

Constants made via #define are simple text substitutions, and have no type per se. Enums, on the other hand, are typesafe (every typedef enum defines a new type), and the compiler can proofread switch statements for unchecked values. AFAIK, they also optimize better than const ints. So... typedef enum { value1, value2, value3 } some_enum; typedef enum { valueA, valueB, valueC } some_other_enum; typedef enum { valueArnie, valueBertha, valueC // Compiler generates an error here: we already used valueC in another enum // #defines would have created a subtle bug here } some_conflicting_enum; void some_func(some_enum foo) { switch(foo) { case value1: /*blah*/ break; case value2: /*more bla*/break; // Compiler generates a warning here: value3 not used in switch statement // use default statement to silence it } } void some_bad_func(some_other_enum bar) { some_func(bar); // Compiler generates a bonafide error } Also, one can have anonymous enums like this (I'll sneak my own question in here if you don't mind): class MyClass { private: enum {state_uninit, state_ok, state_error } state; /*....*/ public: MyClass() {} // state holds which value now? }; /*compare and contrast*/ #define STATE_UNINIT 0 #define STATE_OK 1 #define STATE_ERROR 2 class MyOtherClass { private: int state; /*....*/ public: MyOtherClass() {state=4;} // Compiler accepts this without complaining. Bad Compiler! }; Unless you brutally abuse casts, enum variables are constrained in the values they can contain
5. ## Theoretical upper force limit for ODE particle system?

Quote:Original post by h4tt3n I'm wondering if there is a way to actually calculate the highest possible force a particle system can hande without blowing up? I realise that this at least depends on the used integration scheme (or at least its order of magnitude), the timestep, and particle mass. Other than that I'm lost. Cheers, Mike My memory is a bit hazy on that matter, so all is IIRC. In a sense, yes. Keywords for this question are for example A-stability and Dahlquist. To answer this question for a particular integration scheme amounts to constructing a characteristic function and checking where in |C its magnitude is smaller than 1. Consider the test equation y'=-lambda.y to understand why: The exact solution converges to zero. A numerical solution must do the same: write the scheme as y(k+1)=f(y(k),dt), then this means that |f(y(k),dt)| < |y(k)|. Most numerical methods are linear in y, so one can write f(y,t)=y.R(lambda.t), where p is the function we are interested in. So, with z:=lambda.t our criterion is |R(z)|<1. Notes: All explicit schemes (read: the simple ones) get unstable if lambda gets large enough. All explicit Runge-Kutta-methods of order s have the same R, and it's a polynomial of degree s, namely the Taylor-polynomial of exp(z). I can't find any links to actual graphs at the moment, though.
6. ## Help me get angle

Quote: If i would create imaginary circle whose center is in middle of line CircleCenter -> Point, and radius is D/2, would that new circle intersect with old circle in points i need? Yes. http://en.wikipedia.org/wiki/Thales'_theorem
7. ## gliding simulator

Quote:Original post by grisu I have my speedvector, I call it v, where all forces get added up. I transform this vector into my glider's space. Then I calculate the vectors for lift and drag. Angle of attack is calculated with the dot product of lift and my glider's "up". I don't have realistic values, i play around with constants, so the values for drag and lift are simply calculated with: v*v*alpha*const I transform v into global space and add the gravity-vector. v has units m/s, drag and lift as forces have kg m/s^2, gravity acts as simple acceleration m/s^2. I hope you do multiply the forces with Timestep/Mass, or whatever identifiers you use. Lift and drag coefficients for gliders, as well as wing area, span, etc...can be researched on the web to get initial values, Wikipedia is your friend. Use consistent units, do not optimize constants like air density away on the first try. Quote: Now this is my problem: When the speed gets very high, I fly with a low angle of attack, still a lot of lift is produced, of course. This high lift vector, which is added to the v vector, causes the v vector to point "more up". This, in the next frame, leads to a negative angle of attack, lift vector points downwards, and my values freak out. This effect starts slowly, I can see it from my alpha values, and then explodes. Welcome to numerical mathematics, sounds like your time steps are too big, resulting in numerical instabilities (if you haven't a bug in your code. We can't tell, as we haven't seen it yet). You can either: 1) (easy) decouple physics frame rate from rendering frame rate, and increase the former (calculate more frames than you render) or 2) (hard) study some numerical math and use better methods (Verlet-Integration, explicit Runge-Kutta-methods, or if the problem really does not go away, implicit methods).
8. ## Logic to keep vehicle on course.

Let's see if I can help. Get paper, pencil, ruler and compass. 1) If I understand you correctly, the vehicle starts at A, is supposed to head towards B along AB first, but then to arrive at C from the direction BC. That means we first head straight towards B, but shortly before we reach it we have to steer towards C, following an arc of a circle for a while till we head towards C, then straight again, till we are at C. Said circle has a given radius r (our turning radius) and must be tangent to both AB and BC. Its center M must lie on the ray bisecting the angle alpha=ABC, and the distance between AB and M (and BC and M as well) must equal r. Some trigonometry gives me that |BM|=r/cos(alpha/2). That should be enough to construct the circle and more importantly its tangent point to AB, at which you start turning. 2) Yes, you'll have to turn twice. The second turning circle with center M2 is tangent to BC, and goes through B. The first one with center M! is tangent to AB in a point T1, lies on the other side of AB than C and is tangent to the second one in P2. M2 can be easily found: BM2 is orthogonal on BC, and has length r. M1 lies r away from AB on the other side of C, and is 2r away from M2. That should be enough to construct both circles, P1 where you start turning away from C, and P2=(M1+M2)/2, where you turn towards C again. Neither gives you a simple function from position to steering angle, but state transistion criteria instead: when to switch from heading straight at B from turning left/right, when to turn the steering wheel the other way around, when to head straight towards C. Sounds a lot like a finite state machine to me.
9. ## Handedness

Quote:Original post by lucky6969b I am having difficulties understanding the inverse function done by the author. Can I assume that he was using pivoting for a 4x4 matrix? I am cross-checking it with a reference, but not too sure how he did that. Thanks Jack Try to look up Cramer's_rule, that's what he seems to be doing. There is probably no pivoting going on, only computation of several determinants.
10. ## Missile guidance... iiiiin spaaaaace

Here's an idea: Without loss of generality, we can assume that the missile is at rest at the origin (do a boat trip in remembrance of Gallileo Gallilei). So we have a target at position p, with a velocity v and maybe an acceleration a. We want to know which acceleration b for our missile results in a hit. Well, that's actually quite easy, if the missile hits after a time t, then the acceleration it used was obviously b=2*(p+v*t+a/2*t^2)/t^2. So, how do you want to choose t? One possibility would be to minimize delta-vee spent, that is, t*|b| should be minimal. We know that b can be written as a function of t, and we take the square to avoid pesky roots: f(t):=t^2 * <b(t),b(t)> is to be minimized. That means we want f'(t) to be zero. This problem could be solved via, say, Newton iteration (eat an apple in remembrance of Sir Isaac, and gaze at the moon). Another possibility is to demand full thrust, if you're in a hurry: f(t)=<b(t),b(t)>-(a_max)^2 is to be zero.
11. ## Challenge: Interception Formula

If it isn't homework... If I understand the problem correctly: Player and Target start at given positions P and T. The target is moving into a fixed direction at a fixed speed vt. The player desires to intercept, and can travel with a maximum speed vp. Solution: Define the "Angle on Bow" AOB to be the angle between the target's velocity vector and the vector P-T from target to player. We want to know the lead angle L needed for interception. Geometric construction: Draw a ray B from T through P. Draw another one, H, from T in the direction the target is travelling. Choose an arbitrary timespan t. Taking a compass, mark the point M on H that is t*vp away from P. Draw a circle C with center in M and radius t*vt. There are the following cases: 1) C does not intersect B: Intercept is not possible. 2) C and B intercept in exactly one point I, or touch each other at I: Intercept is feasible in exactly one way, or marginally so. The player must travel paralell to the vector M-I (at full speed). 3) C and B intercept at two points I1 and I2: The player has the choice between a "head-on" intercept and letting the target "hit you in the back" (for this to happen, vt must be greater than vp). Calculation of lead angle: Follows trivially from above construction and basic trigonometry. (Law of sines. The resulting equation cannot always be solved for L, and the ambiguity may or may not correspond to a future event) Bonus 1: Simply pretend in your calculations that one of the tow gets a 500ms head start? Bonus 2: I've read an answer to this one in an old submariner's manual that's on the web somewhere: If you don't have solid data, constanty move perpendicular to the line of sight. There are two cases: 1) Needing to turn towards him, you eventually wind up dead ahead of the target, and are in perfect position for a torpedo attack 2) You notice that you would have to pull away. You are as close as you can get when you are on a paralell course with him. Bonus 3: Trivial. Since there are only two vectors of interest (his course vector and the line of sight) the problem is fundamentally two-dimensional.
12. ## Convexity question

This looks to me lime you could look into linear programming. You only need the first part of the Simplex algorithm that concerns itself with finding a "basic feasible solution". There is - to my knowledge - no guarantee that the algorithm will finish fast enough. All I can offer for now are two keywords for wikipedia: Kirkpatrick-Seidel algorithm and Chan's algorithm for computing the convex hull. If I am not completly asleep today, your first question can be answered reasonably fast, here's a quick idea and a few questions: Compute the extremal points {E1...Eh} of {P1,...,Pn,Q} (Q1: is this the same as computing the convex hull?) Clearly, if Q is not an extremal point, it lies within the convex hull of {P1,..,Pn}, and we are done. (Q2: Can this be right? This would mean that the problem has a runtime of O(n log h), just like Chan's algorithm. The second part, writing Q as a "balanced" convex combination (I made that term up), should be suitable for a least squares algorithm. Out of curiosity, what was the original 3D problem?
13. ## The Cerebral Side of Mining

In theory, there is no difference between theory and practice. In practice, the theoretical part of mining is called geology. A highly skilled miner knows how to get lots and lotsa rocks out of a given spot, safely, quickly and efficiently. A well-learned gelogist can tell the miner what to expect if he starts digging at a certain spot, or where to look for mineral X (an experienced miner will take a pretty good guess himself). A competent metallurgist/stonemason/chemist/whatever can tell both of them what to look for in the first place, and an economist would tell them how much to charge for the stuff, if they were so stupid and ask him instead of the market. The closest description of "theoretical part of fighting" I can think of is "sports medicine", with a strong focus on anatomy and forensics. (This might not be the appropriate place for the following joke: "What's the difference between a mole and a doctor who's bad at anatomy? None, both dig in the dark and produce mounds of earth."). A swordsman also might acquire some vocabulary in metallurgy, to understand whether piercing weapons are better against plate and cutting against mail (or was it the other way round?), to tell the smith how he wants his sword made ("The last one had way to much of its cross-section hardened, and became so brittle as a result that it effing shattered, and it wouldn't keep its edge anyway. Really, much more tempering this time, please!") and to judge the sword he's holding in his hands. I think the main fallacy is not to assume a dichotomy between theory and practice. The fallacy is to assume that each theoretical field corresponds to exactly one application, and vice versa. Once geology helped you get the ore, you need some chemistry to process it, for example. Nitpick to a previous poster: ITYM "piece of ore" instead of "scrap of metal", unless you were referring to a scrap heap or native metals (some metals can only be found as ores). Then again, how economic can it be to dig through someone else's overburden for pebbles of ore, if you can dig in your own claim and get in the habit of separating them neatly in two heaps?

Quote:Original post by Tetragrammatonn [...]the values range from 0 to 15, and I need to show changes as small as 0.5. Quote:Original post by kru Why do the numbers have to be decimals? Would it be so difficult to multiply every related value by 10, and do away with the ugly period? Scaling by 2 instead of 10 would keep both the numbers small and matches the representation by integers to the desired resolution. However, if I may ask a seemingly off-topic question: Why aren't the values integers to begin with? Changing the problem from displaying floats to displaying integers might simplify things. Another idea: Show the values by a simple dial with a up/down trend indicator, and provide precise values via tool tip (the real life metaphor: You can get a rough estimate by a quick look at a mirrored scale, but for an accurate reading you have to move your head over it. A battery can have a voltage meter parallel to it, indicating charge, and an amperemeter in series, to indicate charge/discharge rate).
15. ## how can i call member function from Callback method

(I will read this as "No, it's not homework".) Then what about // this is somewhere else in your code MyClass *obj; // this is the callback result callback LLKeyboardProc( int nCode,WPARAM wParam,LPARAM lParam ) { obj->doit(); } Obviously, somewhere else you will have to call obj=new MyClass(); or you will get a runtime error. However, if your class definition looks like class MyClass { public: static void doit(); }; (Which I was hinting at in my first post, by the way, TWICE, in fact) then you can and must write (and maybe that's what you were asking for result callback LLKeyboardProc( int nCode,WPARAM wParam,LPARAM lParam ) { MyClass::doit(); } I hope my snippets are correct and are helpful to you.