Search Results

Search found 343 results on 14 pages for 'subtract'.

Page 11/14 | < Previous Page | 7 8 9 10 11 12 13 14  | Next Page >

  • Need to format character precedence in Strings.

    - by Christian
    I'm currently writing a Roman Numeral Converter for the fun of it. The problem works up to the aforementioned character precedence. Since Roman Numerals are not positional, i.e. III does not symbolize 1*whatever base^2 + 1*whatever base^1 + 1*whatever base^0. That of course makes it hard when somebody types in XIV and I need to make sure that the I is not added in this case, but rather subtracted. I'm not sure how to do this. What would be the best approach to tackle this? I have both the Roman Symbols and their respective decimal numbers stored in arrays: const char cRomanArray[] = "IVXLCDM"; const int romanArray[] = { 1, 5, 10, 50, 100, 500, 1000 }; so it wouldn't be too hard for me to brute-force the damn thing by simply checking the precedence within the array, i.e. if the symbol is smaller than the next symbol, i.e. in the exampe 'XIV' if 'I' is smaller than 'V', in which case it would be because I have ordered them in the array, then I could make it subtract the value instead of add. But this seems like a very ugly solution. Are there perhaps any better ones? I was thinking something along the lines of Regular Expressions maybe( forgive me if that sounds like a horrible idea, I haven't used RegExp yet, but it sounds like it could do what I need, and that's to determine the characters in a string.)

    Read the article

  • Odd Linq behavior with IList / IEnumerable

    - by Aren B
    I've got the following code: public IList<IProductViewModel> ChildProducts { get; set; } public IList<IProductViewModel> GiftItems { get; set; } public IList<IProductViewModel> PromoItems { get; set; } public IList<IProductViewModel> NonGiftItems { get { return NonPromoItems.Except(GiftItems, new ProductViewModelComparer()).ToList(); } } public IList<IProductViewModel> NonPromoItems { get { return ChildProducts.Where(p => !p.IsPromotion).ToList(); } } So basically, NonPromoItems is (ChildProducts - PromoItems) and NonGiftItems is (NonPromoItems - GiftItems) However When: ChildProducts = IEnumerable<IProductViewModel>[6] PromoItems = IEnumerable<IProductViewModel>[1] where item matches 1 item in ChildProducts GiftItems = IEnumerable<IProductViewModel>[0] My Result is NonPromoItems = IEnumerable<IProductViewModel>[5] This is Correct NonGiftItems = IEnumerable<IProductViewModel>[4] This is Incorrect Somehow an Except(...) is removing an item when given an empty list to subtract. Any ideas anyone?

    Read the article

  • Is there something wrong with this code? AMFReader vs AMFWriter

    - by Triynko
    Something doesn't seem right about the source code for Flash Remoting's Date(AS3) <- DateTime(.NET) stream reader/writer methods, when it comes to handling UTC <- Local times. It seems to write the DateTime data fine, including a 64-bit representation as milliseconds elapsed since Jan 1, 1970, as well as a UTC offset. public void WriteDateTime(DateTime d) { this.BaseStream.WriteByte(11); DateTime time = new DateTime(0x7b2, 1, 1); long totalMilliseconds = (long)d.Subtract(time).TotalMilliseconds; long l = BitConverter.DoubleToInt64Bits((double)totalMilliseconds); this.WriteLong(l); int hours = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Today).Hours; this.WriteShort(hours); } But when the data is read... it seems to be ignoring the short UTC offset value that was written, and appears to just discard it! private DateTime ReadDateValue() { long num2 = (long)this.ReadDouble(); DateTime time2 = new DateTime(0x7b2, 1, 1).AddMilliseconds((double)num2); int num3 = this.ReadInt16() / 60; //num3 is not used for anything! return time2; } Can anyone make sense of this? I also found some similar source code for AMFReader here, which has a ReadDateTime method, that seems to do something very similar... but goes on to use the UTC offset for something.

    Read the article

  • Inner angle between two lines

    - by ocell
    Hi folks, I have two lines: Line1 and Line2. Each line is defined by two points (P1L1(x1, y1), P2L1(x2, y2) and P1L1(x1, y1), P2L3(x2, y3)). I want to know the inner angle defined by these two lines. For do it I calculate the angle of each line with the abscissa: double theta1 = atan(m1) * (180.0 / PI); double theta2 = atan(m2) * (180.0 / PI); After to know the angle I calculate the following: double angle = abs(theta2 - theta1); The problem or doubt that I have is: sometimes I get the correct angle but sometimes I get the complementary angle (for me outer). How can I know when subtract 180º to know the inner angle? There is any algorithm better to do that? Because I tried some methods: dot product, following formula: result = (m1 - m2) / (1.0 + (m1 * m2)); But always I have the same problem; I never known when I have the outer angle or the inner angle! Thanks in advance for reading my trouble and for your time! Oscar.

    Read the article

  • How to prevent external translation of a movieclip object on stage in AS3?

    - by Aaron H.
    I have a MovieClip object, which is exported for actionscript (AS3) in an .swc file. When I place an instance of the clip on the stage without any modifications, it appears in the upper left corner, about half off stage (i.e. only the lower right quadrant of the object is visible). I understand that this is because the clip has a registration point which is not the upper left corner. If you call getBounds() on the movieclip you can get the bounds of the clip (presumably from the "point" that it's aligned on) which looks something like (left: -303, top: -100, right: 303, bottom: 100), you can subtract the left and top values from the clip x and y: clip.x -= bounds.left; clip.y -= bounds.top; This seems to properly align the clip fully on stage with the top left of the clip squarely in the corner of the stage. But! Following that logic doesn't seem to work when aligning it on the center of the stage! clip.x = (stage.stageWidth / 2); etc... This creates the crazy parallel universe where the clip is now down in the lower right corner of the stage. The only clue I have is that looking at: clip.transform.matrix and clip.transform.concatenatedMatrix matrix has a tx value of 748 (half of stage height) ty value of 426 (Half of stage height) concatenatedMatrix has a tx value of 1699.5 and ty value of 967.75 That's also obviously where the movieclip is getting positioned, but why? Where is this additional translation coming from?

    Read the article

  • VBA: How go I get the total width from all controls in an MS-Access form?

    - by Stefan Åstrand
    Hi, This is probably very basic stuff, but please bear in mind I am completely new to these things. I am working on a procedure for my Access datasheet forms that will: Adjust the width of each column to fit content Sum the total width of all columns and subtract it from the size of the window's width Adjust the width of one of the columns to fit the remaining space This is the code that adjusts the width of each column to fit content (which works fine): Dim Ctrl As Control Dim Path As String Dim ClmWidth As Integer 'Adjust column width to fit content For Each Ctrl In Me.Controls If TypeOf Ctrl Is TextBox Then Path = Ctrl.Name Me(Path).ColumnWidth = -2 End If Next Ctrl How should I write the code so I get the total width of all columns? Thanks a lot! Stefan Solution This is the code that makes an Access datasheet go from this: To this: Sub AdjustColumnWidth(frm As Form, clm As String) On Error GoTo HandleError Dim intWindowWidth As Integer ' Window width property Dim ctrl As Control ' Control Dim intCtrlWidth As Integer ' Control width property Dim intCtrlSum As Integer ' Control width property sum Dim intCtrlAdj As Integer ' Control width property remaining after substracted intCtrSum 'Adjust column width to standard width For Each ctrl In frm.Controls If TypeOf ctrl Is TextBox Or TypeOf ctrl Is CheckBox Or TypeOf ctrl Is ComboBox Then Path = ctrl.Name frm(Path).ColumnWidth = 1500 End If Next ctrl 'Get total column width For Each ctrl In frm.Controls If TypeOf ctrl Is TextBox Or TypeOf ctrl Is CheckBox Or TypeOf ctrl Is ComboBox Then Path = ctrl.Name intCtrlWidth = frm(Path).ColumnWidth If Path <> clm Then intCtrlSum = intCtrlSum + intCtrlWidth End If End If Next ctrl 'Adjust column to fit window intWindowWidth = frm.WindowWidth - 270 intCtrlAdj = intWindowWidth - intCtrlSum frm.Width = intWindowWidth frm(clm).ColumnWidth = intCtrlAdj Debug.Print "Totalt (Ctrl): " & intCtrlSum Debug.Print "Totalt (Window): " & intWindowWidth Debug.Print "Totalt (Remaining): " & intCtrlAdj Debug.Print "clm : " & clm HandleError: GeneralErrorHandler Err.Number, Err.Description Exit Sub End Sub Code to call procedure: Private Sub Form_Load() Call AdjustColumnWidth(Me, "txtDescription") End Sub

    Read the article

  • ActionScript Tweening Matrix Transform (big problem)

    - by TheDarkIn1978
    i'm attempting to tween the position and angle of a sprite. if i call the functions without tweening, to appear in one step, it's properly set at the correct coordinates and angle. however, tweening it makes it all go crazy. i'm using an rotateAroundInternalPoint matrix, and assume tweening this along with coordinate positions is messing up the results. works fine (without tweening): public function curl():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle); backCanvas.transform.matrix = internalPointMatrix; } doesn't work properly (with tweening): public function curlUp():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; distanceTween = new Tween(parameters, "distance", None.easeNone, 0, distance, 1, true); angleTween = new Tween(parameters, "angle", None.easeNone, 0, angle, 1, true); angleTween.addEventListener(TweenEvent.MOTION_CHANGE, animateCurl); } private function animateCurl(evt:TweenEvent):void { backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle - previousAngle); backCanvas.transform.matrix = internalPointMatrix; previousAngle = parameters.angle; } in order for the angle to tween properly, i had to add a variable that would track it's last angle setting and subtract it from the new one. however, i still can not get this tween to return the same end position and angle as is without tweening. i've been stuck on this problem for a day now, so any help would be greatly appreciated.

    Read the article

  • Performance Difference between HttpContext user and Thread user

    - by atrueresistance
    I am wondering what the difference between HttpContext.Current.User.Identity.Name.ToString.ToLower and Thread.CurrentPrincipal.Identity.Name.ToString.ToLower. Both methods grab the username in my asp.net 3.5 web service. I decided to figure out if there was any difference in performance using a little program. Running from full Stop to Start Debugging in every run. Dim st As DateTime = DateAndTime.Now Try 'user = HttpContext.Current.User.Identity.Name.ToString.ToLower user = Thread.CurrentPrincipal.Identity.Name.ToString.ToLower Dim dif As TimeSpan = Now.Subtract(st) Dim break As String = "nothing" Catch ex As Exception user = "Undefined" End Try I set a breakpoint on break to read the value of dif. The results were the same for both methods. dif.Milliseconds 0 Integer dif.Ticks 0 Long Using a longer duration, loop 5,000 times results in these figures. Thread Method run 1 dif.Milliseconds 125 Integer dif.Ticks 1250000 Long run 2 dif.Milliseconds 0 Integer dif.Ticks 0 Long run 3 dif.Milliseconds 0 Integer dif.Ticks 0 Long HttpContext Method run 1 dif.Milliseconds 15 Integer dif.Ticks 156250 Long run 2 dif.Milliseconds 156 Integer dif.Ticks 1562500 Long run 3 dif.Milliseconds 0 Integer dif.Ticks 0 Long So I guess what is more prefered, or more compliant with webservice standards? If there is some type of a performance advantage, I can't really tell. Which one scales to larger environments easier?

    Read the article

  • Algorithm for count-down timer that can add on time

    - by Person
    I'm making a general timer that has functionality to count up from 0 or count down from a certain number. I also want it to allow the user to add and subtract time. Everything is simple to implement except for the case in which the timer is counting down from some number, and the user adds or subtracts time from it. For example: (m_clock is an instance of SFML's Clock) float Timer::GetElapsedTime() { if ( m_forward ) { m_elapsedTime += m_clock.GetElapsedTime() - m_elapsedTime; } else { m_elapsedTime -= m_elapsedTime - m_startingTime + m_clock.GetElapsedTime(); } return m_elapsedTime; } To be a bit more clear, imagine that the timer starts at 100 counting down. After 10 seconds, the above function would look like 100 -= 100 - 100 + 10 which equals 90. If it was called after 20 more seconds it would look like 90 -= 90 - 100 + 30 which equals 70. This works for normal counting, but if the user calls AddTime() ( just m_elapsedTime += arg ) then the algorithm for backwards counting fails miserably. I know that I can do this using more members and keeping track of previous times, etc. but I'm wondering whether I'm missing some implementation that is extremely obvious. I'd prefer to keep it as simple as possible in that single operation.

    Read the article

  • Issue in setting alarm time in AlarmManager Class

    - by Anshuman
    I have used the following code in setting alarm time in AlarmManager class. Now Suppose my device current date 9-july-2012 11:31:00, Now suppose i set set a alarm at 9-july-2012 11:45:00, then it works fine and pop-up an alarm at that time. But if i set an alarm at 10-aug-2012 11:40:00, then as soon as exit the app the alarm pop-up, which is wrong because i set an alarm at month of august, So why this happen, is anything wrong in my code. if anyone knows help me to solve this out. Code For Setting Alarm time in AlarmManager class Intent myIntent = new Intent(context, AlarmService.class); PendingIntent pendingIntent = PendingIntent.getService(context, i, myIntent, i); AlarmManager alarmManager = (AlarmManager)context.getSystemService(AlarmService.ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.MILLISECOND, (int) dateDifferenceFromSystemTime(NoteManager.getSingletonObject().getAlarmTime(i))); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); public static long dateDifferenceFromSystemTime(Date date) { long difference = 0; try { Calendar c = Calendar.getInstance(); difference = date.getTime() - c.getTimeInMillis(); if (difference < 0) { // if difference is -1 - means alarm time is of previous time then current // then firstly change it to +positive and subtract form 86400000 to get exact new time to play alarm // 86400000-Total no of milliseconds of 24hr Day difference = difference * -1; difference = 86400000 - difference; } } catch (Exception e) { e.printStackTrace(); } return difference; } Service class which pop-up alarm when matches time public class AlarmService extends IntentService { public void onCreate() { super.onCreate(); } public AlarmService() { super("MyAlarmService"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, startId, startId); return START_STICKY; } @Override protected void onHandleIntent(Intent intent) { startActivity(new Intent(this,AlarmDialogActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } }

    Read the article

  • Using SQL dB column as a lock for concurrent operations in Entity Framework

    - by Sid
    We have a long running user operation that is handled by a pool of worker processes. Data input and output is from Azure SQL. The master Azure SQL table structure columns are approximated to [UserId, col1, col2, ... , col N, beingProcessed, lastTimeProcessed ] beingProcessed is boolean and lastTimeProcessed is DateTime. The logic in every worker role is: public void WorkerRoleMain() { while(true) { try { dbContext db = new dbContext(); // Read foreach (UserProfile user in db.UserProfile .Where(u => DateTime.UtcNow.Subtract(u.lastTimeProcessed) > TimeSpan.FromHours(24) & u.beingProcessed == false)) { user.beingProcessed = true; // Modify db.SaveChanges(); // Write // Do some long drawn processing here ... ... ... user.lastTimeProcessed = DateTime.UtcNow; user.beingProcessed = false; db.SaveChanges(); } } catch(Exception ex) { LogException(ex); Sleep(TimeSpan.FromMinutes(5)); } } // while () } With multiple workers processing as above (each with their own Entity Framework layer), in essence beingProcessed is being used a lock for MutEx purposes Question: How can I deal with concurrency issues on the beingProcessed "lock" itself based on the above load? I think read-modify-write operation on the beingProcessed needs to be atomic but I'm open to other strategies. Open to other code refinements too.

    Read the article

  • exception in thread "main" java.lang.NoclassDefFoundError: cal/class

    - by Gaurav
    enter import java.io.*; class eval { double add(double a,double b) { return (a+b); } double sub(double a,double b) { return (a-b); } double mul(double a,double b) { return (a*b); } double div(double a,double b) { return (a/b); } } class cal extends eval { public static void main(String args[])throws IOException { eval a1=new eval(); try{ System.out.println("1) Add"); System.out.println("2) Subtract"); System.out.println("3) Multiply"); System.out.println("4) Divide"); System.out.println("5) Enter your choice"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int ch;ch=Integer.parseInt(br.readLine()); System.out.println("Enter two number"); double a;a=Integer.parseInt(br.readLine()); double b;b=Integer.parseInt(br.readLine()); switch(ch) { case 1: a1.add(a,b); break; case 2: a1.sub(a,b); break; case 3: a1.mul(a,b); break; case 4: a1.div(a,b); break; } } catch (IOException e) { System.out.println("Error occured, please restart application."); } } }

    Read the article

  • Problems sorting by date

    - by Nathan
    I'm attempting to only display data added to my database 24 hours ago or less. However, for some reason, the code I've written isn't working, and both entries in my database, one from 1 hour ago, one from 2 days ago, show up. Is there something wrong with my equation? Thanks! public void UpdateValues() { double TotalCost = 0; double TotalEarned = 0; double TotalProfit = 0; double TotalHST = 0; for (int i = 0; i <= Program.TransactionList.Count - 1; i++) { DateTime Today = DateTime.Now; DateTime Jan2013 = DateTime.Parse("01-01-2013"); //Hours since Jan12013 int TodayHoursSince2013 = Convert.ToInt32(Math.Round(Today.Subtract(Jan2013).TotalHours)); //7 int ItemHoursSince2013 = Program.TransactionList[i].HoursSince2013; //Equals 7176, and 7130 if (ItemHoursSince2013 - TodayHoursSince2013 <= 24) { TotalCost += Program.TransactionList[i].TotalCost; TotalEarned += Program.TransactionList[i].TotalEarned; TotalProfit += Program.TransactionList[i].TotalEarned - Program.TransactionList[i].TotalCost; TotalHST += Program.TransactionList[i].TotalHST; } } label6.Text = "$" + String.Format("{0:0.00}", TotalCost); label7.Text = "$" + String.Format("{0:0.00}", TotalEarned); label8.Text = "$" + String.Format("{0:0.00}", TotalProfit); label10.Text = "$" + String.Format("{0:0.00}", TotalHST); }

    Read the article

  • Groovy as a substitute for Java when using BigDecimal?

    - by geejay
    I have just completed an evaluation of Java, Groovy and Scala. The factors I considered were: readability, precision The factors I would like to know: performance, ease of integration I needed a BigDecimal level of precision. Here are my results: Java void someOp() { BigDecimal del_theta_1 = toDec(6); BigDecimal del_theta_2 = toDec(2); BigDecimal del_theta_m = toDec(0); del_theta_m = abs(del_theta_1.subtract(del_theta_2)) .divide(log(del_theta_1.divide(del_theta_2))); } Groovy void someOp() { def del_theta_1 = 6.0 def del_theta_2 = 2.0 def del_theta_m = 0.0 del_theta_m = Math.abs(del_theta_1 - del_theta_2) / Math.log(del_theta_1 / del_theta_2); } Scala def other(){ var del_theta_1 = toDec(6); var del_theta_2 = toDec(2); var del_theta_m = toDec(0); del_theta_m = ( abs(del_theta_1 - del_theta_2) / log(del_theta_1 / del_theta_2) ) } Note that in Java and Scala I used static imports. Java: Pros: it is Java Cons: no operator overloading (lots o methods), barely readable/codeable Groovy: Pros: default BigDecimal means no visible typing, least surprising BigDecimal support for all operations (division included) Cons: another language to learn Scala: Pros: has operator overloading for BigDecimal Cons: some surprising behaviour with division (fixed with Decimal128), another language to learn

    Read the article

  • F# numeric associations

    - by b1g3ar5
    I have a numeric association for a custom type as follows: let DiffNumerics = { new INumeric<Diff> with member op.Zero = C 0.0 member op.One = C 1.0 member op.Add(a,b) = a + b member op.Subtract(a,b) = a - b member op.Multiply(a,b) = a * b member ops.Negate(a) = Diff.negate a member ops.Abs(a) = Diff.abs a member ops.Equals(a, b) = ((=) a b) member ops.Compare(a, b) = Diff.compare a b member ops.Sign(a) = int (Diff.sign a).Val member ops.ToString(x,fmt,fmtprovider) = failwith "not implemented" member ops.Parse(s,numstyle,fmtprovider) = failwith "not implemented" } GlobalAssociations.RegisterNumericAssociation(DiffNumerics) It works fine in f# interactive, but crashes when I run, because .ElementOps is not filled correctly for a matrix of these types. Any ideas why this might be? EDIT: In fsi, the code let A = dmatrix [[Diff.C 1.;Diff.C 2.;Diff.C 3.];[Diff.C 4.;Diff.C 5.;Diff.C 6.]] let B = matrix [[1.;2.;3.];[4.;5.;6.]] gives: > A.ElementOps;; val it : INumeric<Diff> = FSI_0003.NewAD+DiffNumerics@258 > B.ElementOps;; val it : INumeric<float> = Microsoft.FSharp.Math.Instances+FloatNumerics@115 > in the debugger A.ElementOps shows: '(A).ElementOps' threw an exception of type 'System.NotSupportedException' and, for the B matrix: Microsoft.FSharp.Math.Instances+FloatNumerics@115 So somehow the DiffNumerics isn't making it to the compiled program.

    Read the article

  • How can change my code to can user insert numbers of year and days ?

    - by MANAL
    I make code to calculate the date of today and the date for two years ago before the day of today and also calculate day before 5 days. I want user insert the numbers of years and days to make compare between date of today . import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; import java.util.Scanner; public class Calendar1 { private static void doCalendarTime() { System.out.print("*************************************************"); Date now = Calendar.getInstance().getTime(); System.out.print(" \n Calendar.getInstance().getTime() : " + now); System.out.println(); } private static void doSimpleDateFormat() { System.out.print("*************************************************"); System.out.print("\n\nSIMPLE DATE FORMAT\n"); System.out.print("*************************************************"); // Get today's date Calendar now = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.print(" \n It is now : " + formatter.format(now.getTime())); System.out.println(); } private static void doAdd() { System.out.println("ADD / SUBTRACT CALENDAR / DATEs"); System.out.println("================================================================="); // Get today's date Calendar now = Calendar.getInstance(); Calendar working; SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); working = (Calendar) now.clone(); working.add(Calendar.DAY_OF_YEAR, - (365 * 2)); System.out.println (" Two years ago it was: " + formatter.format(working.getTime())); working = (Calendar) now.clone(); working.add(Calendar.DAY_OF_YEAR, + 5); System.out.println(" In five days it will be: " + formatter.format(working.getTime())); System.out.println(); } public static void main(String[] args) { System.out.println(); doCalendarTime(); doSimpleDateFormat(); doAdd(); } } help me .

    Read the article

  • How do I make this nested for loop, testing sums of cubes, more efficient?

    - by Brian J. Fink
    I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program. The code for the program is below: import java.lang.*; import java.math.*; public class FindFib { public static void main(String args[]) { long uLimit=9223372036854775807L; //long maximum value BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D); //Golden Ratio for(long a=1;a<=uLimit;a++) //Outer Loop, 1 to maximum for(long b=1;b<=a;b++) //Inner Loop, 1 to current outer { //Cube the numbers and add BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3)); System.out.print(c+" "); //Output result //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c] BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)), e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)); //Mobius test: if integer in interval (floor values unequal) Fibonacci number! if (d.toBigInteger().compareTo(e.toBigInteger())!=0) System.out.println(); //Line feed else System.out.print("\r"); //Carriage return instead } //Display final message System.out.println("\rDone. "); } } Now the use of BigDecimal and BigInteger was delibrate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?

    Read the article

  • Delphi: How to avoid EIntOverflow underflow when subtracting?

    - by Ian Boyd
    Microsoft already says, in the documentation for GetTickCount, that you could never compare tick counts to check if an interval has passed. e.g.: Incorrect (pseudo-code): DWORD endTime = GetTickCount + 10000; //10 s from now ... if (GetTickCount > endTime) break; The above code is bad because it is suceptable to rollover of the tick counter. For example, assume that the clock is near the end of it's range: endTime = 0xfffffe00 + 10000 = 0x00002510; //9,488 decimal Then you perform your check: if (GetTickCount > endTime) Which is satisfied immediatly, since GetTickCount is larger than endTime: if (0xfffffe01 > 0x00002510) The solution Instead you should always subtract the two time intervals: DWORD startTime = GetTickCount; ... if (GetTickCount - startTime) > 10000 //if it's been 10 seconds break; Looking at the same math: if (GetTickCount - startTime) > 10000 if (0xfffffe01 - 0xfffffe00) > 10000 if (1 > 10000) Which is all well and good in C/C++, where the compiler behaves a certain way. But what about Delphi? But when i perform the same math in Delphi, with overflow checking on ({Q+}, {$OVERFLOWCHECKS ON}), the subtraction of the two tick counts generates an EIntOverflow exception when the TickCount rolls over: if (0x00000100 - 0xffffff00) > 10000 0x00000100 - 0xffffff00 = 0x00000200 What is the intended solution for this problem? Edit: i've tried to temporarily turn off OVERFLOWCHECKS: {$OVERFLOWCHECKS OFF}] delta = GetTickCount - startTime; {$OVERFLOWCHECKS ON} But the subtraction still throws an EIntOverflow exception. Is there a better solution, involving casts and larger intermediate variable types?

    Read the article

  • Can this be done using LINQ/Lambda, C#3.0

    - by Newbie
    Objective: Generate dates based on Week Numbers Input: StartDate, WeekNumber Output: List of dates from the Week number specified till the StartDate i.e. If startdate is 23rd April, 2010 and the week number is 1, then the program should return the dates from 16th April, 2010 till the startddate. The function public List<DateTime> GetDates(DateTime startDate,int weeks) { List<DateTime> dt = new List<DateTime>(); int days = weeks * 7; DateTime endDate = startDate.AddDays(-days); TimeSpan ts = startDate.Subtract(endDate); for (int i = 0; i <= ts.Days; i++) { DateTime dt1 = endDate.AddDays(i); dt.Add(dt1); } return dt; } I am calling this function as DateTime StartDate = DateTime.ParseExact("20100423", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); List<DateTime> dtList = GetDates(StartDate, 1); The program is working fine. Question is using C# 3.0 feature like Linq, Lambda etc. can I rewrite the program. Why? Because I am learning linq and lambda and want to implement the same. But as of now the knowledge is not sufficient to do the same by myself. Thanks.

    Read the article

  • is this a design pattern?

    - by Michel
    Hi all, i have to build some financial data report, and for making the calculation, there are a lot of 'if then' situations: if it's a large client, subtract 10%, if it's postal code equals '10101', add 10%, if the day is on a saturday, make a difficult calculation etc. so i once read about this kind of example, and what they did was (hope i remember well) create a class with some base info and make it possible to add all kinds of calculationobjects to it. So to put what i remembered in pseudo code Basecalc bc = new baseCalc(); //put the info in the bc so other objects can do their if bc.Add(new Largecustomercalc()); bc.Add(new PostalcodeCalc()); bc.add(new WeekdayCalc()); the the bc would run the Calc() methods of all of the added Calc objects. As i type this i think all the Calc objects must be able to see the Basecalc properties to correctly perform their calculation logic. So all the if's are in the different Calc objects and not ALL in the Basecalc. does this make sense? I was wondering if this is some kind of design pattern?

    Read the article

  • Recursive code Sorting in VB

    - by Peter
    Ages old question: You have 2 hypothetical eggs, and a 100 story building to drop them from. The goal is to have the least number of guaranteed drops that will ensure you can find what floor the eggs break from the fall. You can only break 2 eggs. Using a 14 drop minimum method, I need help writing code that will allow me to calculate the following: Start with first drop attempt on 14th floor. If egg breaks then drop floors 1-13 to find the floor that causes break. ElseIf egg does not break then move up 13 floors to floor number 27 and drop again. If egg breaks then drop floors 15-26 starting on 15 working up to find the floor egg breaks on. ElseIf egg does not break then move up 12 floors to floor number 39 and drop again. etc. etc. The way this increases is as follows 14+13+12+11+10+9+8+7+6+5+4+3+2+1 So always adding to the previous value, by one less. I have never written a sorting algorithm before, and was curious how I might go about setting this up in a much more efficient way than a mile long of if then statements. My original idea was to store values for the floors in an array, and pull from that, using the index to move up or down and subtract or add to the variables. The most elegant solution would be a recursive function that handled this for any selected floor, 1-100, and ran the math, with an output that shows how many drops were needed in order to find that floor. Maximum is always 14, but some can be done in less.

    Read the article

  • Optimizing this "Boundarize" method for Numerics in Ruby

    - by mstksg
    I'm extending Numerics with a method I call "Boundarize" for lack of better name; I'm sure there are actually real names for this. But its basic purpose is to reset a given point to be within a boundary. That is, "wrapping" a point around the boundary; if the area is betweeon 0 and 100, if the point goes to -1, -1.boundarize(0,100) = 99 (going one too far to the negative "wraps" the point around to one from the max). 102.boundarize(0,100) = 2 It's a very simple function to implement; when the number is below the minimum, simply add (max-min) until it's in the boundary. If the number is above the maximum, simply subtract (max-min) until it's in the boundary. One thing I also need to account for is that, there are cases where I don't want to include the minimum in the range, and cases where I don't want to include the maximum in the range. This is specified as an argument. However, I fear that my current implementation is horribly, terribly, grossly inefficient. And because every time something moves on the screen, it has to re-run this, this is one of the bottlenecks of my application. Anyone have any ideas? module Boundarizer def boundarize min=0,max=1,allow_min=true,allow_max=false raise "Improper boundaries #{min}/#{max}" if min >= max new_num = self if allow_min while new_num < min new_num += (max-min) end else while new_num <= min new_num += (max-min) end end if allow_max while new_num > max new_num -= (max-min) end else while new_num >= max new_num -= (max-min) end end return new_num end end class Numeric include Boundarizer end

    Read the article

  • What to call factory-like (java) methods used with immutable objects

    - by StaxMan
    When creating classes for "immutable objects" immutable meaning that state of instances can not be changed; all fields assigned in constructor) in Java (and similar languages), it is sometimes useful to still allow creation of modified instances. That is, using an instance as base, and creating a new instance that differs by just one property value; other values coming from the base instance. To give a simple example, one could have class like: public class Circle { final double x, y; // location final double radius; public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } // method for creating a new instance, moved in x-axis by specified amount public Circle withOffset(double deltaX) { return new Circle(x+deltaX, y, radius); } } So: what should method "withOffset" be called? (note: NOT what its name ought to be -- but what is this class of methods called). Technically it is kind of a factory method, but somehow that does not seem quite right to me, since often factories are just given basic properties (and are either static methods, or are not members of the result type but factory type). So I am guessing there should be a better term for such methods. Since these methods can be used to implement "fluent interface", maybe they could be "fluent factory methods"? Better suggestions? EDIT: as suggested by one of answers, java.math.BigDecimal is a good example with its 'add', 'subtract' (etc) methods. Also: I noticed that there's this question (by Jon Skeet no less) that is sort of related (although it asks about specific name for method)

    Read the article

  • Glassfish complaining about JSF component IDs

    - by Brian
    Hello All I am very new to JSF (v2.0) and I am attempting to learn it at places like netbeans.org and coreservlets.com. I am working on a very simple "add/subtract/multiply/divide" Java webapp and I have run into a problem. When I first started out, the application was enter two numbers and hit a '+' key and they would be automatically added together. Now that I have added more complexity I am having trouble getting the operation to the managed bean. This is what I had when it was just "add": <h:inputText styleClass="display" id="number01" size="4" maxlength="3" value="#{Calculator.number01}" /> <h:inputText styleClass="display" id="number02" size="4" maxlength="3" value="#{Calculator.number02}" /> <h:commandButton id="add" action="answer" value="+" /> For the "answer" page, I display the answer like this: <h:outputText value="#{Calculator.answer}" /> I had the proper getters and setters in the Calculator.java managed bean and the operation worked perfectly. Now I have added the other three operations and I am having trouble visualizing how to get the operation parameter to the bean so that I can switch around it. I tried this: <h:commandButton id="operation" action="answer" value="+" /> <h:commandButton id="operation" action="answer" value="-" /> <h:commandButton id="operation" action="answer" value="*" /> <h:commandButton id="operation" action="answer" value="/" /> However, Glassfish complained that I have already used "operation" once and I am trying to use it four times here. Any adivce/tips on how to get multiple operations to the managed bean so that it can preform the desired operation? Thank you for taking the time to read.

    Read the article

  • Question about CALL statement

    - by Bruce
    I have the following code in VC++ Func5(){ StackWalk(); } Func4{ Func5();} I am a Beginner in x86 Assembly Language. I am trying to find out the starting address of Func5(). I get the Func5()'s return address from its stack frame. Now before this return address there should be a CALL statement. So I extract out the bytes before the return address. Sometimes it's a near call like E8 ff ff ff d8. So for this statement I subtract the offset 0x28 from the function's return address to get Func5()'s base address (where it resides in memory). The problem is I don't know how to calculate this for a indirect NEAR call. I have been trying to find out how to do it for some time now. So I have extracted out the first 5 bytes before the return address and they are ff 75 08 ff d2 I think this stands for CALL ECX (ff d2) but I am not sure. I will be very grateful if someone can tell me what kind of CALL statement this is and how I can calculate the function's base address from this kind of call.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14  | Next Page >