Simple arithmetic

Hi abapers,
I'm confused on what has been doing wrong in my codes.
The situation is i have variables
v1 type p decimals 2.
v2 type p decimals 2.
i passed the value from ekpo-menge to v1 and same with v2.
i have a variable of v3 with type p decimals 2.
for example v1 = 6, v2 = 3.
when i tried to divide v1 / v2. i get a quotient of 0.01. I expected to get answer of 2 but i get 0.01.
Why is that? I'm working in an enhancement of ME22N.

Hi James Evert Lising,
in EKPO table...
Details of MENGE field...
MENGE     QUAN     13     3     Purchase Order Quantity
Here MENGE is having 3 decimal places...
Try to declare all related variables as
VAR1 type P decimals 3.
Also check the values of variable V1 and V2 in debugging mode... Modify the lengh of a variable accordingly...
while creating ur report u should check the check box of Fixed point arithmatic in attributes... Just check it out from Program attributes... GoTo --> Attributes...
Also have a look on below code it's giving proper result...
REPORT ZILESH_TEMP2.
DATA  : TAB_V1 TYPE EKPO-MENGE VALUE '6.000', " OR TAB_V1 TYPE EKPO-MENGE VALUE 6.
        TAB_V2 TYPE EKPO-MENGE VALUE '3.000', " OR TAB_V2 TYPE EKPO-MENGE VALUE 3.
        TAB_V3 TYPE EKPO-MENGE.
DATA : V1 TYPE P DECIMALS 2,
       V2 TYPE P DECIMALS 2,
       V3 TYPE P DECIMALS 2.
V1 = TAB_V1.
V2 = TAB_V2.
V3 = V1 / V2.
TAB_V3 = V3.
WRITE : / V3.
WRITE : / TAB_V3.
Hope it will solve your problem..
Thanks & Regards
ilesh 24x7

Similar Messages

  • Help Needed in developing simple Chatting application using flex and blazeds

    Hi,
    I followed this tutorial from adobe http://learn.adobe.com/wiki/display/Flex/Creating+a+BlazeDS+messaging+application+in+Flex+ Builder i installed tomcat server and set the path.I am unable to open server like this http://localhost:8080 but i can able to open that in this way http://127.0.0.1:8080/   .... When i create my new flex project in flash builder 4 i am getting this error
    You do not have write permission for the project output folder. Specify another location.
    can any one help me in how to get rid of this problem.I hope this forum helps me in finishing my flex project..
    Thanks
    Trinethra

    Hi,
    Need to use a scrollable resultset and depending on the need to have a stateful connection or a stateless connection you may need to query the table for every request(for stateless connection) and use the same result set for(stateful connection). and depending on the no of records in a page and the page no do some simple arithmetic and move the resultset. Hope this helps.
    rajesh

  • Inline functions in C, gcc optimization and floating point arithmetic issues

    For several days I really have become a fan of Alchemy. But after intensive testing I have found several issues which I'd like to solve but I can't without any help.
    So...I'm porting an old game console emulator written by me in ANSI C. The code is working on both gcc and VisualStudio without any modification or crosscompile macros. The only platform code is the audio and video output which is out of scope, because I have ported audio and video witin AS3.
    Here are the issues:
    1. Inline functions - Having only a single inline function makes the code working incorrectly (although not crashing) even if any optimization is enabled or not (-O0 or O3). My current workarround is converting the inline functions to macros which achieves the same effect. Any ideas why inline functions break the code?
    2. Compiler optimizations - well, my project consists of many C files one of which is called flash.c and it contains the main and exported functions. I build the project as follows:
    gcc -c flash.c -O0 -o flash.o     //Please note the -O0 option!!!
    gcc -c file1.c -O3 -o file1.o
    gcc -c file2.c -O3 -o file2.o
    ... and so on
    gcc *.o -swc -O0 -o emu.swc   //Please note the -O0 option again!!!
    mxmlc.exe -library-path+=emu.swc --target-player=10.0.0 Emu.as
    or file in $( ls *.o ) //Removes the obj files
        do
            rm $file
        done
    If I define any option different from -O0 in gcc -c flash.c -O0 -o flash.o the program stops working correctly exactly as in the inline funtions code (but still does not crash or prints any errors in debug). flash has 4 static functions to be exported to AS3 and the main function. Do you know why?
    If I define any option different from -O0 in gcc *.o -swc -O0 -o emu.swc  the program stops working correctly exactly as above, but if I specify -O1, -O2 or O3 the SWC file gets smaller up to 2x for O3. Why? Is there a method to optimize all the obj files except flash.o because I suspect a similar issue as when compilling it?
    3. Flating point issues - this is the worst one. My code is mainly based on integer arithmetic but on 1-2 places it requires flating point arithmetic. One of them is the conversion of 16-bit 44.1 Khz sound buffer to a float buffer with same sample rate but with samples in the range from -1.0 to 1.0.
    My code:
    void audio_prepare_as()
        uint32 i;
        for(i=0;i<audioSamples;i+=2)
            audiobuffer[i] = (float)snd.buffer[i]/32768;
            audiobuffer[i+1] = (float)snd.buffer[i+1]/32768;
    My audio playback is working perfectly. But not if using the above conversion and I have inspected the float numbers - all incorrect and invalid. I tried other code with simple floats - same story. As if alchemy refuses to work with floats. What is wrong? I have another lace whre I must resize the framebuffer and there I have a float involved - same crap. Please help me?
    Found the floating point problem: audiobuffer is written to a ByteArray and then used in AS. But C floats are obviously not the same as those in AS3. Now the floating point is resolved.
    The optimization issues remain! I really need to speed up my code.
    Thank you in advice!

    Dear Bernd,
    I am still unable to run the optimizations and turn on the inline functions. None of the inline functions contain any stdli function just pure asignments, reads, simple arithmetic and bitwise operations.
    In fact, the file containing the main function and those functions for export in AS3 did have memset and memcpy. I tried your suggestion and put the code above the functions calling memset and memcpy. It did not work soe I put the code in a header which is included topmost in each C file. The only system header I use is malloc.h and it is included topmost. In other C file I use pow, sin and log10 from math.h but I removed it and made the same thing:
    //shared.h
    #ifndef _SHARED_H_
    #define _SHARED_H_
    #include <malloc.h>
    static void * custom_memmove( void * destination, const void * source, unsigned int num ) {
      void *result; 
      __asm__("%0 memmove(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num)); 
      return result; 
    static void * custom_memcpy ( void * destination, const void * source, unsigned int num ) { 
      void *result; 
      __asm__("%0 memcpy(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num)); 
      return result; 
    static void * custom_memset ( void * ptr, int value, unsigned int num ) { 
      void *result; 
      __asm__("%0 memset(%1, %2, %3)\n" : "=r"(result) : "r"(ptr), "r"(value), "r"(num)); 
      return result; 
    static float custom_pow(float x, int y) {
        float result;
      __asm__("%0 pow(%1, %2)\n" : "=r"(result) : "r"(x), "r"(y));
      return result;
    static double custom_sin(double x) {
        double result;
      __asm__("%0 sin(%1)\n" : "=r"(result) : "r"(x));
      return result;
    static double custom_log10(double x) {
        double result;
      __asm__("%0 log10(%1)\n" : "=r"(result) : "r"(x));
      return result;
    #define memmove custom_memmove
    #define memcpy custom_memcpy
    #define memset custom_memset
    #define pow custom_pow
    #define sin custom_sin
    #define log10 custom_log10 
    #include "types.h"
    #include "macros.h"
    #include "m68k.h"
    #include "z80.h"
    #include "genesis.h"
    #include "vdp.h"
    #include "render.h"
    #include "mem68k.h"
    #include "memz80.h"
    #include "membnk.h"
    #include "memvdp.h"
    #include "system.h"
    #include "loadrom.h"
    #include "input.h"
    #include "io.h"
    #include "sound.h"
    #include "fm.h"
    #include "sn76496.h" 
    #endif /* _SHARED_H_ */ 
    It still behave the same way as if nothing was changed (works incorrectly - displays jerk which does not move, whereby the image is supposed to move)
    As I am porting an emulator (Sega Mega Drive) I use manu arrays of function pointers for implementing the opcodes of the CPU's. Could this be an issue?
    I did a workaround for the floating point problem but processing is very slow so I hear only bzzt bzzt but this is for now out of scope. The emulator compiled with gcc runs at 300 fps on a 1.3 GHz machine, whereby my non optimized AVM2 code compiled by alchemy produces 14 fps. The pure rendering is super fast and the problem lies in the computational power of AVM. The frame buffer and the enulation are generated in the C code and only the pixels are copied to AS3, where they are plotted in a BitmapData. On 2.0 GHz Dual core I achieved only 21 fps. Goal is 60 fps to have smooth audio and video. But this is offtopic. After all everything works (slow) without optimization, and I would somehow turn it on. Suggestions?
    Here is the file with the main function:
    #include "shared.h"
    #include "AS3.h"
    #define FRAMEBUFFER_LENGTH    (320*240*4)
    static uint8* framebuffer;
    static uint32  audioSamples;
    AS3_Val sega_rom(void* self, AS3_Val args)
        int size, offset, i;
        uint8 hardware;
        uint8 country;
        uint8 header[0x200];
        uint8 *ptr;
        AS3_Val length;
        AS3_Val ba;
        AS3_ArrayValue(args, "AS3ValType", &ba);
        country = 0;
        offset = 0;
        length = AS3_GetS(ba, "length");
        size = AS3_IntValue(length);
        ptr = (uint8*)malloc(size);
        AS3_SetS(ba, "position", AS3_Int(0));
        AS3_ByteArray_readBytes(ptr, ba, size);
        //FILE* f = fopen("boris_dump.bin", "wb");
        //fwrite(ptr, size, 1, f);
        //fclose(f);
        if((size / 512) & 1)
            size -= 512;
            offset += 512;
            memcpy(header, ptr, 512);
            for(i = 0; i < (size / 0x4000); i += 1)
                deinterleave_block(ptr + offset + (i * 0x4000));
        memset(cart_rom, 0, 0x400000);
        if(size > 0x400000) size = 0x400000;
        memcpy(cart_rom, ptr + offset, size);
        /* Free allocated file data */
        free(ptr);
        hardware = 0;
        for (i = 0x1f0; i < 0x1ff; i++)
            switch (cart_rom[i]) {
         case 'U':
             hardware |= 4;
             break;
         case 'J':
             hardware |= 1;
             break;
         case 'E':
             hardware |= 8;
             break;
        if (cart_rom[0x1f0] >= '1' && cart_rom[0x1f0] <= '9') {
            hardware = cart_rom[0x1f0] - '0';
        } else if (cart_rom[0x1f0] >= 'A' && cart_rom[0x1f0] <= 'F') {
            hardware = cart_rom[0x1f0] - 'A' + 10;
        if (country) hardware=country; //simple autodetect override
        //From PicoDrive
        if (hardware&8)        
            hw=0xc0; vdp_pal=1;
        } // Europe
        else if (hardware&4)    
            hw=0x80; vdp_pal=0;
        } // USA
        else if (hardware&2)    
            hw=0x40; vdp_pal=1;
        } // Japan PAL
        else if (hardware&1)      
            hw=0x00; vdp_pal=0;
        } // Japan NTSC
        else
            hw=0x80; // USA
        if (vdp_pal) {
            vdp_rate = 50;
            lines_per_frame = 312;
        } else {
            vdp_rate = 60;
            lines_per_frame = 262;
        /*SRAM*/   
        if(cart_rom[0x1b1] == 'A' && cart_rom[0x1b0] == 'R')
            save_start = cart_rom[0x1b4] << 24 | cart_rom[0x1b5] << 16 |
                cart_rom[0x1b6] << 8  | cart_rom[0x1b7] << 0;
            save_len = cart_rom[0x1b8] << 24 | cart_rom[0x1b9] << 16 |
                cart_rom[0x1ba] << 8  | cart_rom[0x1bb] << 0;
            // Make sure start is even, end is odd, for alignment
            // A ROM that I came across had the start and end bytes of
            // the save ram the same and wouldn't work.  Fix this as seen
            // fit, I know it could probably use some work. [PKH]
            if(save_start != save_len)
                if(save_start & 1) --save_start;
                if(!(save_len & 1)) ++save_len;
                save_len -= (save_start - 1);
                saveram = (unsigned char*)malloc(save_len);
                // If save RAM does not overlap main ROM, set it active by default since
                // a few games can't manage to properly switch it on/off.
                if(save_start >= (unsigned)size)
                    save_active = 1;
            else
                save_start = save_len = 0;
                saveram = NULL;
        else
            save_start = save_len = 0;
            saveram = NULL;
        return AS3_Int(0);
    AS3_Val sega_init(void* self, AS3_Val args)
        system_init();
        audioSamples = (44100 / vdp_rate)*2;
        framebuffer = (uint8*)malloc(FRAMEBUFFER_LENGTH);
        return AS3_Int(vdp_rate);
    AS3_Val sega_reset(void* self, AS3_Val args)
        system_reset();
        return AS3_Int(0);
    AS3_Val sega_frame(void* self, AS3_Val args)
        uint32 width;
        uint32 height;
        uint32 x, y;
        uint32 di, si, r;
        uint16 p;
        AS3_Val fb_ba;
        AS3_ArrayValue(args, "AS3ValType", &fb_ba);
        system_frame(0);
        AS3_SetS(fb_ba, "position", AS3_Int(0));
        width = (reg[12] & 1) ? 320 : 256;
        height = (reg[1] & 8) ? 240 : 224;
        for(y=0;y<240;y++)
            for(x=0;x<320;x++)
                di = 1280*y + x<<2;
                si = (y << 10) + ((x + bitmap.viewport.x) << 1);
                p = *((uint16*)(bitmap.data + si));
                framebuffer[di + 3] = (uint8)((p & 0x1f) << 3);
                framebuffer[di + 2] = (uint8)(((p >> 5) & 0x1f) << 3);
                framebuffer[di + 1] = (uint8)(((p >> 10) & 0x1f) << 3);
        AS3_ByteArray_writeBytes(fb_ba, framebuffer, FRAMEBUFFER_LENGTH);
        AS3_SetS(fb_ba, "position", AS3_Int(0));
        r = (width << 16) | height;
        return AS3_Int(r);
    AS3_Val sega_audio(void* self, AS3_Val args)
        AS3_Val ab_ba;
        AS3_ArrayValue(args, "AS3ValType", &ab_ba);
        AS3_SetS(ab_ba, "position", AS3_Int(0));
        AS3_ByteArray_writeBytes(ab_ba, snd.buffer, audioSamples*sizeof(int16));
        AS3_SetS(ab_ba, "position", AS3_Int(0));
        return AS3_Int(0);
    int main()
        AS3_Val romMethod = AS3_Function(NULL, sega_rom);
        AS3_Val initMethod = AS3_Function(NULL, sega_init);
        AS3_Val resetMethod = AS3_Function(NULL, sega_reset);
        AS3_Val frameMethod = AS3_Function(NULL, sega_frame);
        AS3_Val audioMethod = AS3_Function(NULL, sega_audio);
        // construct an object that holds references to the functions
        AS3_Val result = AS3_Object("sega_rom: AS3ValType, sega_init: AS3ValType, sega_reset: AS3ValType, sega_frame: AS3ValType, sega_audio: AS3ValType",
            romMethod, initMethod, resetMethod, frameMethod, audioMethod);
        // Release
        AS3_Release(romMethod);
        AS3_Release(initMethod);
        AS3_Release(resetMethod);
        AS3_Release(frameMethod);
        AS3_Release(audioMethod);
        // notify that we initialized -- THIS DOES NOT RETURN!
        AS3_LibInit(result);
        // should never get here!
        return 0;

  • Incorrect arithmetic in bigdecimal

    Hello,
    I attempting to do some simple arithmetic (for FX rate conversion) using BigDecimal that is generating incorrect results (while the same calculation with double works correctly).
    Can someone please take a look at this sample program and tell me what I may be doing wrong? Or, at least provide some insight into what is going wrong so that I can take steps to avoid?
    import static java.math.RoundingMode.HALF_UP;
    import java.math.BigDecimal;
    import java.math.MathContext;
    public class BigDecimalTest {
          public static void main(String[] args) {
                // 15,000,000,000,000
                BigDecimal large_value = new BigDecimal("15000000000000");
                MathContext mc = new MathContext(16, HALF_UP);
                BigDecimal divisor = new BigDecimal("1.5");
                BigDecimal numerator = BigDecimal.ONE.divide(divisor, mc);
                BigDecimal resultOne = large_value.multiply(numerator);
                BigDecimal resultTwo = large_value.divide(divisor, mc);
                System.out.println("Big Decimal arithmetic:");
                System.out.println("15 trillion * (1/1.5) = ["+resultOne.toPlainString()+"]");
                System.out.println("15 trillion / 1.5 = ["+resultTwo.toPlainString()+"]");
                System.out.println("results compare as ["+resultOne.compareTo(resultTwo)+"]\n");
                double large_dbl_value = 15000000000000d;
                double divisorDbl = 1.5;
                double resultOneDbl = large_dbl_value * (1/divisorDbl);
                double resultTwoDbl = large_dbl_value / divisorDbl;
                System.out.println("double arithmetic:");
                System.out.println("15 trillion * (1/1.5) = ["+resultOneDbl+"]");
                System.out.println("15 trillion /1.5 = ["+resultTwoDbl+"]");
                System.out.println("results compare as ["+(resultOneDbl - resultTwoDbl)+"]");
    }Thank you,
    Ed Bridges

    When I look more into the proposed solution -- for example in the code below -- I still see discrepancies in the arithmetic of BigDecimal and double:
    import static java.math.RoundingMode.HALF_UP;
    import java.math.BigDecimal;
    import java.math.MathContext;
    public class BigDecimalTest {
         public static void main(String[] args) {
              // 12,345,678,901,234
              BigDecimal large_value = new BigDecimal("12345678901234");
              MathContext mc = new MathContext(16, HALF_UP);
              for (int i = 80; i< 90; i++) {           
                   BigDecimal rate = new BigDecimal(i).divide(new BigDecimal("100.0"));
                   BigDecimal divisor = rate.setScale(16, HALF_UP);
                   BigDecimal numerator = divisor.pow(-1, mc);
                   BigDecimal resultOne = large_value.multiply(numerator).round(mc);
                   BigDecimal resultTwo = large_value.divide(divisor, mc);
                   if (resultOne.compareTo(resultTwo)!= 0) {
                        System.out.println("Big Decimal arithmetic:");
                        System.out.println(large_value + " * (1/" + rate + ") = ["+resultOne.toPlainString()+"]");
                        System.out.println(large_value + " / " + rate + " = ["+resultTwo.toPlainString()+"]");
                        System.out.println("results compare as ["+resultOne.compareTo(resultTwo)+"]\n");
              double large_dbl_value = 12345678901234d;
              for (int i = 80; i< 90; i++) {           
                   double divisorDbl = i / 100;
                   double resultOneDbl = large_dbl_value * (1/divisorDbl);
                   double resultTwoDbl = large_dbl_value / divisorDbl;
                   if (resultOneDbl != resultTwoDbl) {
                        System.out.println("double arithmetic:");
                        System.out.println(large_dbl_value + " * (1/" + divisorDbl + ") = ["+resultOneDbl+"]");
                        System.out.println(large_dbl_value + " / " + divisorDbl + " = ["+resultTwoDbl+"]");
                        System.out.println("results compare as ["+(resultOneDbl - resultTwoDbl)+"]");
    }This produces the following result:
    Big Decimal arithmetic:
    12345678901234 * (1/0.86) = [14355440582830.24]
    12345678901234 / 0.86 = [14355440582830.23]
    results compare as [1]
    Big Decimal arithmetic:
    12345678901234 * (1/0.89) = [13871549327229.22]
    12345678901234 / 0.89 = [13871549327229.21]
    results compare as [1]It's these "off-by-one penny" errors that are killing me :-(

  • A Simple Calculator

    Well, im currently doing a Java Module which i really dont want to do because im not so good at Java.. anyway i want to split a string on a certain char, but this char will change depending what the users inputs... so i tried the following:
    c0perator = sInput.charAt(indexOperator);                
    String[] sNumbers = sInput.split(c0perator); but i get an error "cannot find symbol - method split(char)".. i want to know how i can get this towork.. i have tried it with the following line an it works
    String[] sNumbers = sInput.split("+"); but i want the + to be able to change if you get me... see full code below
    import java.util.Scanner;
    public class part3
         public static void main (String[] args)
           Scanner keyboard = new Scanner (System.in); // keyboard input
           //Variables
           String sInput;
           char c0perator = 56;
           int indexAdd, indexMin, indexMul, indexDiv, index1, index2, indexOperator;
           double answer = 0, firstNo = 0, secondNo = 0;
           // Input
           System.out.println("Enter a calcutation in following format '<number> <Operator> <number>' ");
           System.out.println("operator can be replaced with +,-,* and /. Enter Data: ");
           sInput = keyboard.nextLine();    //Data entry
           System.out.println("");
           // Process & Output
            // Searchs for operators
           indexAdd = sInput.indexOf('+');
           indexMin = sInput.indexOf('-');
           indexMul = sInput.indexOf('*');
           indexDiv = sInput.indexOf('/');
           index1 =(indexAdd>indexMin) ? indexAdd: indexMin;            //Index1 = indexAdd if greater...
           index2 =(indexMul>indexDiv) ? indexMul: indexDiv;            //Index2 = indexMul if greater...
           indexOperator = (index1>index2) ? index1: index2;           //IndexOperator = index if greater...
           if (indexOperator < 0) {                                     // if operator was not found then
               System.out.println("ERROR!");
            } else {
                c0perator = sInput.charAt(indexOperator);                  //locates the operator
                String[] sNumbers = sInput.split(c0perator);               //Splits the string where Operator is found
                String sFirstNo = sNumbers[0]; // first number
                String sSecondNo = sNumbers[1]; //second number
                sFirstNo = sFirstNo.trim(); //Trims all spacing off
                sSecondNo = sSecondNo.trim(); //Trims all spacing off
                firstNo = Double.parseDouble(sFirstNo);  //Converts first number to Int
                secondNo = Double.parseDouble(sSecondNo);  //Converts second number to Int
           switch ( c0perator ) {
            case '+':       // Addition
                answer = firstNo+secondNo;
                break;
            case '-':       // Subtraction
                answer = firstNo-secondNo;
                break;
            case '*':       // Multiplication
                answer = firstNo*secondNo;
                break;
            case '/':       // Division
                answer = firstNo/secondNo;
                break;
            case 'E':       // Opperator not found
                System.out.println("Operator Not Found - Error!");
            default:        // Default error
                System.out.println("Format Operator Error: " + c0perator);
            System.out.println("The answer is: " + answer);
    }

    Only + and * are reserved (of the 4 simple arithmetic operators) and need to be escaped:
    String[] array;
    array = "1+2".split("\\+");
    System.out.println(array[0]+"+"+array[1]);
    array = "1-2".split("-");
    System.out.println(array[0]+"-"+array[1]);
    array = "1/2".split("/");
    System.out.println(array[0]+"/"+array[1]);
    array = "1*2".split("\\*");
    System.out.println(array[0]+"*"+array[1]);

  • Regex for arithmetic expressions

    Hi all,
    I am new to Java. I was wondering if anyone can help me understand how regular expressions work. My problem is how to come up with a regular expression that would match a simple arithmetic expression like:
    a + b + c + d
    And I want to capture things by groups. I largely suspect that I should use something like:
    (\\w+)(\\s\\+\\s(\\w+))*
    (I use the \\s here because \\b doesn't seem to work)
    would work by capturing the first word like sequence with (\\w+), and the succeeding repeats of the plus sign and another word being captured by (\\s\\+\\s(\\w+))*. Didn't work though. Can anyone tell me what's wrong and how to think of a better way of handling these sort of expressions?
    The code I tried goes like:
    String patt = "(\\w+)(\\s\\+\\s(\\w+))*";
    String feed = "a + b + c + d";
    Pattern p = Pattern.compile(patt);
    Matcher m = p.matcher(feed);
    /* here I want to see if the groupings work somehow*/
    if(m.find()){
    for(int i=0; i<=m.groupCount(); i++)
    System.out.println(m.group(i));
    Thanks

    Sorry about that. Here's the correctly formatted post:
    So, with a simple arithmetic expression like:
    a + b + c + dI want to capture things by groups and I thought of using something like:
    (\\w+)(\\s\\+\\s(\\w+))*(I use the \\s here because \\b doesn't seem to work)
    with the idea of capturing the first word like sequence with (\\w+), and the succeeding repeats of the plus sign and another word being captured by (\\s\\+\\s(\\w+))*. As this didn't work, can anyone tell me what's wrong and how to think of a better way of handling these sort of expressions?
    The code I tried goes like:
    String patt = "(\\w+)(\\s\\+\\s(\\w+))*";
    String feed = "a + b + c + d";
    Pattern p = Pattern.compile(patt);
    Matcher m = p.matcher(feed);then I want to see if the groupings work somehow
    if(m.find()){
    for(int i=0; i<=m.groupCount(); i++)
    System.out.println(m.group(i));
    }and yes, I am wondering if arithmetic parsing would be possible with regex. I have implemented something similar before using combinations of simple tokenization and character checks, but I want to make cleaner looking code. Would using regular expressions be a bad choice? What if I feed something like:
    (a + b) + (c + d)

  • How to find square root, log recursively???

    I need to find the square root of a number entered recursively and log as well. Your help would be greatly appreciated. Thanks in advance!
    import java.io.*;
    /**Class provides recursive versions
    * of simple arithmetic operations.
    public class Ops2
         private static BufferedReader in = null;
         /**successor, return n + 1*/
         public static int suc(int n)
              return n + 1;
         /**predecessor, return n - 1*/
         public static int pre(int n)
              if (n == 0)
                   return 0;
              else
                   return n - 1;
         /**add two numbers entered*/
         public static int add(int n, int m)
              if (m == 0)
                   return n;
              else
                   return suc(add(n, pre(m)));
         /**subtract two numbers entered*/
         public static int sub(int n, int m)
              if (n < m)
                   return 0;
              else if (m == 0)
                   return n;
              else
                   return pre(sub(n, pre(m)));
         /**multiply two numbers entered*/
         public static int mult(int n, int m)
              if (m == 0)
                   return 0;
              else
                   return add(mult(n, pre(m)), n);
         /**divide two numbers entered*/
         public static int div(int n, int m)
              if (n < m)
                   return 0;
              else
                   return suc(div(sub(n, m), m));
         /**raise first number to second number*/
         public static int exp(int n, int m)
              if (m == 0)
                   return 1;
              else
                   return mult(exp(n, pre(m)), n);
         /**log of number entered*/
         public static int log(int n)
              if (n < 2)
                   return 0;
              else
                   return suc(log(div(n, 2)));
         /**square root of number entered*/
         public static int sqrt(int n)
              if (n == 0)
                   return 0;
              else
                   return sqrt(div(n, ));
         /**remainder of first number entered divided by second number*/
         public static int mod(int n, int m)
              if (n < m)
                   return 0;
              else
                   return mod(div(n, pre(m)), m);
         public static void prt(String s)
              System.out.print(s);
         public static void prtln(String s)
              System.out.println(s);
         public static void main(String [ ] args)
              prtln("Welcome to the amazing calculator");
              prtln("It can add, multiply and do powers for");
              prtln("naturals (including 0). Note that all the");
              prtln("HARDWARE does is add 1 or substract 1 to any number!!");
              in = new BufferedReader(new InputStreamReader ( System.in ) );
              int It;
              while ( (It = getOp()) >= 0)
                   prt("" + It + "\n");
            private static int getOp( )
            int first, second;
            String op;
            try
                System.out.println( "Enter operation:" );
                do
                    op = in.readLine( );
                } while( op.length( ) == 0 );
             System.out.println( "Enter first number: " );
                first = Integer.parseInt( in.readLine( ) );
                System.out.println( "Enter second number: " );
                second = Integer.parseInt( in.readLine( ) );
             prtln("");
             prt(first + " " + op + " " + second + " = ");
                switch( op.charAt( 0 ) )
                  case '+':
                    return add(first, second);
                  case '-':
                       return sub(first, second);
                  case '*':
                    return mult(first, second);
                  case '/':
                       return div(first, second);
                  case '^':
                    return exp(first, second);
                  case 'v':
                       return log(first);
                  case 'q':
                       return sqrt(first);
                  case '%':
                       return mod(first, second);
                  case 's':
                       return suc(first);
                  case 'p':
                       return pre(first);
                  default:
                    System.err.println( "Need +, *, or ^" );
                    return -1;
            catch( IOException e )
                System.err.println( e );
                return  0;
    }

    Hi,
    Is there any one to make a program for me in Turbo
    C++ for Dos, which can calculate the square root of
    any number without using the sqrt( ) or any ready
    made functions.
    The program should calculate the s.root of the number
    by a formula or procedure defined by the user
    (programmer).
    Thanks.This is a Java forum!
    If you want Java help:
    1. Start your own thread.
    2. Use code tags (above posting box) if you post code.
    3. No one will write the program for you. We will help by answering your questions and giving advice on how to fix problems in code you wrote.
    4. The formula you need to implement is given above by dizzy.

  • Square root of an interval using Newton's method

    Hello!
    I am trying to create a method that calculates the square root of an interval, and I am having trouble with both the actual calculation part, as well as the base case for the recursion. I implemented a simple counter for the recursion, but was not seeing any kind of pattern for the values. (I am pretty sure the "better" values should converge to 0).
    I was wondering if anybody wanted to take a swing at it and help me out. :)
    Here is the code for my program, followed by the code for Newton's method for calculating square roots of doubles. I am supposed to use it as a reference.
    I made the simple arithmetic methods with the help of http://en.wikipedia.org/wiki/Interval_arithmetic . They seem to work fine, so I am having issues with troubleshooting!
    Thanks!
    public class Interval {
         double x1;
         double x2;
         public Interval(double newx1, double newx2){
              x1 = newx1;
              x2 = newx2;
         public String toString(){
              return "[" + this.x1 + ", " + this.x2 + "]";
         //Add an interval to the current one.
         public Interval add(Interval j){
              double tempx1 = this.x1 + j.x1;
              double tempx2 = this.x2 + j.x2;
              Interval tempInterval = new Interval(tempx1, tempx2);
              return tempInterval;
         //Subtract an interval from the current one.
         public Interval sub(Interval j){
              double tempx1 = this.x1 - j.x2;
              double tempx2 = this.x2 - j.x1;
              Interval tempInterval = new Interval(tempx1, tempx2);
              return tempInterval;
         //Multiply an interval with the current one.
         public Interval mul(Interval j){
                   double minx1 = Math.min(this.x1*j.x1, this.x2*j.x2);
                   double minx2 = Math.min(this.x1*j.x2, this.x2*j.x1);
                   double maxx1 = Math.max(this.x1*j.x1, this.x2*j.x2);
                   double maxx2 = Math.max(this.x1*j.x2, this.x2*j.x1);
                   double tempx1 = Math.min(minx1, minx2);
                   double tempx2 = Math.max(maxx1, maxx2);
                   Interval tempInterval = new Interval(tempx1, tempx2);
                   return tempInterval;
         //Divide the current interval by a new one.
         public Interval div(Interval j){
                   double minx1 = Math.min(this.x1/j.x1, this.x2/j.x2);
                   double minx2 = Math.min(this.x1/j.x2, this.x2/j.x1);
                   double maxx1 = Math.max(this.x1/j.x1, this.x2/j.x2);
                   double maxx2 = Math.max(this.x1/j.x2, this.x2/j.x1);
                   double tempx1 = Math.min(minx1, minx2);
                   double tempx2 = Math.max(maxx1, maxx2);
                   Interval tempInterval = new Interval(tempx1, tempx2);
                   return tempInterval;
         static Interval step(Interval x, Interval y) {
              // Compute a "better" guess than x for the square root of y:
              // Code for doubles: Interval better = x - (x*x - y)/(2*x);
              Interval two = new Interval(2.0, 2.0);
              Interval better = x.sub( ( (x.mul(x)).sub(y) ).div(two.mul(x)) );
              // For doubles:
              if ( Math.abs(better.x2 - better.x1) < 0.001 ) { // base case
                   System.out.println(better.toString());
                   return better;
              else {
                   return step(better, y); // try to get even better...
         static Interval sqrt(Interval y) {
              return step(y, y); //: start guessing at the square root
         public static void main(String args[]){
              Interval i = new Interval(4.0, 8.0);
              Interval j = new Interval(4.0, 8.0);
              Interval addij = i.add(j);
              Interval subij = i.sub(j);
              Interval mulij = i.mul(j);
              Interval divij = i.div(j);
              Interval sqrtj = i.sqrt(j);
              System.out.println("Intervals:");
              System.out.println(i.toString());
              System.out.println(j.toString());
              System.out.println("Add: " + addij.toString());
              System.out.println("Sub: " + subij.toString());
              System.out.println("Mul: " + mulij.toString());
              System.out.println("Div: " + divij.toString());
              System.out.println("Sqrt: " + sqrtj.toString());
    }and newton's root finder for doubles:
    public class SquareRoot {
         static final double ALLOWED_ERROR = 0.001;
          * Newton's method for finding square roots.
         static double step(double x, double y) {
              // Compute a "better" guess than x for the square root of y:
              double better = x - (x*x - y)/(2*x);
              // Are we close enough?
              if ( Math.abs(x - better) < ALLOWED_ERROR ) { // => stop: base case
                   return better;
              else {
                   return step(better, y); // try to get even better...
         static double sqrt(double y) {
              return step(y, y); //: start guessing at the square root
         public static void main(String[] args) {
              System.out.println(Math.sqrt(1234));
              System.out.println(sqrt(1234));
              // NOTE: you may need to adjust the error bound for these two to agree
    }

    Nathron wrote:
    Here is the code for my program, followed by the code for Newton's method for calculating square roots of doubles. I am supposed to use it as a reference.The only thing I can see that looks suspicious is the call to step(better, y) in your reference code.
    Are you sure it shouldn't be step(y, better) or step(better, x))? Newton-Rhapson is supposed to be a progressive method, but as far as I can see the value of y can never change with the way you've got it. And if you've copied that to your new code, it might explain the problem.
    Winston

  • How do I create a dynamic 2xN array?

    Hey All,
    I've got a question that seems pretty easy in concept but for some reason I just can't quite figure it out. All I want to do is run through a matrix using for loops and if a value in that matrix is equal to the value I set (my cutoff value), I take the coordinates (the iterations of the loops) and pop them into an array, which I hope to use as a set of graphable points. So I start out by building a 2x1 1D array from the two points I get (my loop iterations again, which would represent my X and Y values), by using the Build Array VI. Now I try feeding that into another Build Array VI that has a feedback loop on it which feeds back into itself. The output from this is then sent to an Array Size VI (which is outside the loops) so that I can see just how big my 2xN array got.
    Now the good news is that I do get a 2D array as an output. The bad news is that try to get the data exactly when my cut off point occurs (ie. if(data == cutoff) ) I get no size, but if I created a range of even one lower (ie. if( (data <= cutoff) || (data >= (cutoff-1))) ) then the size of my array turn out to be 2x49152, which is the total range of my data (192*256). Now I know for a fact that not every point in my data is one less than my cutoff point (which is the maximum value in this case) as I have a meshing that shows me the values. I also thought that maybe conflicting data types might be a problem, so I converted my cutoff value from a int to a float type. No dice there either. Soooo, I figure it must be some underlying logic that I'm missing or something that LabView does differently than I expect.
    I guess my actual question is this then: Why does LabView gives me either a 0 element array or a complete array (as in ALL the data points not just the ones at the cutoff value)? Also if there is a better way to build the array than this.
    I have attached a picture of my current set up that retrieves the data points, builds the 2xN array and gets the size. If there's any other part that you may need to see, just let me know.
    Thanks,
    Phil
    [url=http://img114.imageshack.us/my.php?image=buildinganarrayjl7.jpg][img=http://img114.imageshack.us/img114/3226/buildinganarrayjl7.th.jpg][/url]
    P.S. Here's an direct link to the image if the above doesn't work: http://img114.imageshack.us/img114/3226/buildinganarrayjl7.jpg

    If I understood you correctly, you want to find the indices where the array element value matches a certain fixed value. One thing you must understand is that you must never perform equality operations on floating point values with computers. Computers operate in base 2, while you operate in base 10. It is not possible to precisely represent a floating point number using computers. This issue comes up a lot. How you choose to do the comparison depends on your numbers and what level of precision you want.
    That said there is no need to use a formula node for simple arithmetic. LabVIEW has functions to do that, and they're much faster than using a formula node. Don't try to write LabVIEW code using text-programming techniques. It won't work. I don't use Feedback Nodes because I hate them. I prefer shift registers since they're much easier to understand, and you can't accidentally flip their direction. Here's a simple implementation using shift registers. That little white plus function is a custom function to check if a floating point value is approximately equal to some value, within a specifed number of decimal places.
    Message Edited by smercurio_fc on 08-12-2008 04:59 PM
    Attachments:
    Example_VI.png ‏10 KB

  • Urgent Help Needed in Developing Pagewise Navigation System

    I have 500 records in the sql server 2000 then i query and retrieve them in a resultsets. and then i want to display 10 records per page having the facility to navigate to the Previous and Next Record also going to first and the last record.
    like we are using when we navigate from this forum
    FIRST PREVIOUS 1 2 3 4 5 6 7 8 9 10 NEXT LAST
    secondly if their is a possiblity their should be a search page to to specific page like this
    Go To this Page (Textfield)
    third thing when i am on first record the it shouldnt show PREVIOUS button and when it is in the last it should not show NEXT.
    this thing should be done by Using JSP , Servelets and Beans...
    and no Tag liabraries. i need pure and simple coding.

    Hi,
    Need to use a scrollable resultset and depending on the need to have a stateful connection or a stateless connection you may need to query the table for every request(for stateless connection) and use the same result set for(stateful connection). and depending on the no of records in a page and the page no do some simple arithmetic and move the resultset. Hope this helps.
    rajesh

  • How to write data from 24 bit card DAQ card unscaled

    Hello
    I have a PXI 4462 Data acquistion card to record data. It is 24 bit card. I have two questions about writing data from this card.
    1) When acquiring the analog signal the card changes the analog to digital and when writing it scales back to analog signal. I want to write the analog signal in the digital form. How can i do that.
    2) PXI 4462 is a 24 bit card, but there is either 16 bit or 32 bit when writing it. So if i write it in 32 bit a byte is not used. only 3 bytes will be used to write the data and one byte wont have any data in it. It takes space on the hard disk. Is there any way to save this one byte so that I will be able to write just 24 bit data without loosing that one byte which would save me plenty of space.
    The sampling rate is usually 96Ks/sec.
    Thanks in advance
    Regards
    Nitin

    If you want to write 24 bits instead of 32, then you have to change the hi(x) to 8 bits instead of 16. The lo(x) will stay at 16 so the 8 plus 16 equals 24 bits. Simple arithmetic. You asked how to get rid of the upper 8 bits and if you leave it at 16, then you haven't gotten rid of anything.
    Why do you think you have to write to separate files? I said do a write of the 16 bit and then a write of of the 8 bit component. It's just two Write File functions to the same file. You could also bundle them together and do a single write but I think there would be a little additional overhead with that.
    Message Edited by Dennis Knutson on 04-06-2006 07:15 AM
    Attachments:
    write binary.JPG ‏5 KB

  • How do you add or subtract a constant from a time channel?

    I have a time channel with an offset I wish to remove. How can I do this? Using simple arithmetic means that I need to know how times and dates are stored internally, but I cannot determine this in the online help.
    e.g. Say I need to subtract 1.2 s from all the values in a time channel, in order to synchronise the data in that group with data in another group. How would I do this?
    Solved!
    Go to Solution.

    Hi PorridgeMan,
    Go to ANALYSIS->Basic Mathematics -> Offset Correction
    Greetings
    Walter

  • 500 gig drive only 465 gig.  Is this normal?

    Hi all,
    whilst I realize that the amount of space you actually get on a drive is less than it is meant to be, how much is acceptable? Actually, it always made me wonder why the available size is not reported accurately, isn't it contravening consumer rights to say one thing and give another???
    Maybe I could go into the Apple store to buy a $2,000 iMac, with an envelope stuffed with cash, and the amount of $2,000 written on the front, but with only $1,850 actually inside. Isn't it the same? Would they give me the $2,000 machine? That aside, here is my issue.
    I have a MBP with a 200 gig drive - actual space available = 185.99 gig. So, I lose 14 gig.
    But the iMac that I took delivery of today has only 465 gig available on the 500 gig drive. So the loss is 35 gig, and that seems like a lot to me.
    Anyone have any thoughts on this?
    Thanks.
    Hugh
    Message was edited by: Hugh Anderson1

    Hi Hugh,
    Hugh Anderson1 wrote:
    Yes, I just noticed that the ratio of "lost" space is the same from my examples. Why don't they just tell you that though?
    Thanks for the input.
    Hugh
    Just to clarify further the responses you have already received. In brief, when you see HD capacity advertised as 60GB, 80GB, 100GB etc, that's the marketing way where they take "decimal" road and base 1GB as being equal to 1,000,000,000 bytes. This is true for all HD manufacturers and computer manufacturers.
    Once upon a time, computer professionals noticed that 1,024 bytes (binary) was very nearly equal to 1,000 (decimal) and started using the prefix "kilo" to mean 1,024. That worked well enough for a decade or two because everybody who talked kilobytes knew that the term implied 1,024 bytes. But, almost overnight a much more numerous "everybody" bought computers, and the trade computer professionals needed to talk to physicists and engineers and even to ordinary people, most of whom know that a kilometer is 1,000 meters and a kilogram is 1,000 grams.
    Often when two or more people begin discussing storage capacity, some will refer to binary values and others will refer to decimal values without making distinction between the two. This has caused much confusion in the past (and still does). In an effort to dispatch this confusion, all major disc drive manufacturers use decimal values when discussing storage capacity.
    Some simple arithmetic will convert the advertised (decimal) capacity to the actual (binary) capacity:
    1KB = 1,024 bytes
    1MB = 1,024 x 1,024 bytes = 1,048,576 bytes
    1GB = 1,024 x 1,024 x 1,024 bytes = 1,073,741,824 bytes
    Therefore, in your specific case:
    500GB (decimal) = 500 ÷ 1.073741824 = 465.66128730774 GB (binary or actual capacity)
    Rounded off to two decimal points = 465.66 GB
    I hope this clarifies it for you and explains the reasons for the discrepancy.
    Kryten

  • What you wanted to know about Time values

    Hello
    I tried to gather in a single document the useful infos about the use of time values in Numbers.
    I must thanks pw1840 which checked the English syntax.
    Here is the text only document.
    Files with the sample tables are available on my iDisk:
    <http://idisk.me.com/koenigyvan-Public?view=web>
    Download:
    ForiWork:ForNumbers:Time in Numbers.zip
    *STORED DATE-TIME VALUES - BASICS*
    Numbers clearly states that it stores date-time values, no less no more. This means these values consist of two parts: a date and a time. It is important to note that both parts are present even if only one of them is displayed.
    When we type the time portion only, it includes the current date even though it may not be displayed.
    But when we apply the formula: =TIME(0,0,ROUND(TIMEVALUE(B)24*6060,0)), we get a date-time value whose numerical value of the date portion is 0. This means, in AppleLand, 1 janvier 1904. Such a date-time allows us to make correct calculations, but there are two true drawbacks:
    1) Since TIMEVALUE() returns a decimal number, when we calculate the corresponding number of seconds we MUST use the ROUND() function. While calculations with decimal numbers give the wanted value, they may not be exact and be off by + or - epsilon. And
    2) The structure of Numbers date-time values is such that the time part is always in the range 0:00:00 thru 23:59:59.
    There is also a detail which seems annoying to some users. The minimal time unit is the second because time values are in fact a pseudo string representing the number of seconds between the date-time and the base date-time, 1 janvier 1904 00:00:00.
    -+-+-+-+-
    *TIMEVALUE() FUNCTION*
    When Numbers Help states that the TIMEVALUE() function "converts a date, a time, or a text string to a decimal fraction of a 24-hour day.", it means that the operand for the function TIMEVALUE() may be something like:
    31/12/1943, 31 décembre 1943, or 31 déc. 1943 described as a date;
    1:12:36 or 1:12 described as time; or
    31/12/1943 23:59:59 described as a text string.
    The date may also be 31/12/43 but here the program must guess the century. According to the rule, this one will be 31/12/2043 (yes, I am very young).
    All of this is not exactly what we are accustomed to but it is perfectly logical as described. My guess is that those who don't understand are simply clinging to old habits and are reluctant to adopt an unfamiliar approach .
    -+-+-+-+-
    *ELAPSED TIME (DURATION)*
    Given a table whose 1st row is a header, I will assume that column B stores starting-time values and column C stores ending-time values. Both do not display the date component of the date-time values. We may get the difference in column D with the formula:
    =IF(OR(ISBLANK(B),ISBLANK(C)),"",TIMEVALUE(C)-TIMEVALUE(B))
    which returns the elapsed time as the decimal part of the day.
    We immediately encounter a problem. If ending-time is the day after the starting-day, the result will be negative. So it would be useful to revise the formula this way:
    =IF(OR(ISBLANK(B),ISBLANK(C)),"",IF(TIMEVALUE(C)>TIMEVALUE(B),0,1)+TIMEVALUE(C) -TIMEVALUE(B))
    But some of us may wish to see results in the traditional format which may be achieved using:
    =IF(OR(ISBLANK(B),ISBLANK(C)),"",TIME(0,0,ROUND((IF(TIMEVALUE(C)>TIMEVALUE(B),0 ,1)+TIMEVALUE(C)-TIMEVALUE(B))24*6060,0)))
    -+-+-+-+-
    *DURATION SUMS > or = 24 HOURS*
    In the examples above, we always assumed that the durations where smaller than 24 hours because Numbers states clearly in the Help and the PDF Users Guide that time values are restricted to the range 00:00:0 to 23:59:59. For longer durations we must fool Numbers.
    First problem: we are adding several time durations. Each duration is in the authorized range and the result is greater than 24 hours.
    As before, starting-time values are in column B, ending-time ones are in column C, and the elapsed time value is in column D. The formula is:
    =IF(OR(ISBLANK(B),ISBLANK(C)),"",IF(TIMEVALUE(C)>TIMEVALUE(B),0,1)+TIMEVALUE(C) -TIMEVALUE(B))
    in column E, the formula for the cumulative elapsed time value is:
    =SUM($D$2:D2)
    in column F, converting to time format, the formula is:
    =TIME(0,0,ROUND(MOD(E,1)24*6060,0))
    in column G, the formula for showing more than 24 hours in the day/hour/minute format is:
    =IF(E<1,"",INT(E)&IF(E<2," day "," days "))&F
    in column H, expressing total elapsed time in total hours using the traditional time format, the formula is:
    =IF(E<1,F,INT(E)*24+LEFT(F,LEN(F)-6)&RIGHT(F,6))
    in column I, expressing total elapsed time in total hours using the traditional time format, an alternate formula is:
    =IF(E<1,F,INT(E)*24+HOUR(F)&":"&RIGHT("00"&MINUTE(F),2)&":"&RIGHT("00"&SECOND(F ),2))
    Of course the user would choose the format used in column G or the one in column I for his table. There is no need to keep all of them. It would be fine to hide column F whose contents are auxiliary.
    Second problem: individual durations may be greater than 23:59:59 hours.
    Again, column B is used to store starting date-time, column C stores ending date-time, and durations are calculated in column D. Since B and C are storing full date-time values, we may use this simple formula to find the duration:
    =C-B
    in column E, the time portion of the duration given in time format is:
    =TIME(0,0,ROUND(MOD(D,1)24*6060,0))
    in column F the formula to show the duration as days/hours/minutes is:
    =IF(D<1,"",INT(D)&IF(D<2," day "," day(s "))&E
    in column G we give the elapsed time in total hours using a time format. The formula is:
    =IF(D<1,E,INT(D)*24+LEFT(E,LEN(E)-6)&RIGHT(E,6))
    in column H we give the elapsed time in total hours using a time format. An alternate formula is:
    =IF(D<1,E,INT(D)*24+HOUR(E)&":"&RIGHT("00"&MINUTE(E),2)&":"&RIGHT("00"&SECOND(E ),2))
    If the duration is greater than 24 hours, the results in columns E and F are not a time value but a string. So the value in column D (which is time duration only) is useful.
    -+-+-+-+-
    *PROBLEM WITH ENTERING TIME*
    When you wish to enter 12:34 but 12 is the number of minutes, remember that Numbers will decipher this as 12 hours and 34 minutes. Simple tip:
    Assuming that your original entry is in column B, then in column C use this formula to align the minutes and seconds for proper Numbers interpretation:
    =IF(ISERROR(TIME(0,LEFT(B,SEARCH(":",B)-1),RIGHT(B,LEN(B)-SEARCH(":",B)))),"",T IME(0,LEFT(B,SEARCH(":",B)-1),RIGHT(B,LEN(B)-SEARCH(":",B))))
    -+-+-+-
    *MISCELLANEOUS NOTES*
    • Of course, the addition of two dates and multiplication or a division applied to one date means nothing and would generate the red triangle announcing a syntax error.
    • We may add a time value to a date-time: If B contains a date-time and C contains a time, the following formula will return the sum of the two values:
    =B+TIMEVALUE(C)
    • We may strip the time value of a full date-time one with the formula: =DATE(YEAR(B),MONTH(B),DAY(B))
    • Just as a reminder,
    =EDATE(B, 3) adds 3 months to the pure date stored in B
    so, of course,
    =EDATE(B, 12) adds one year to the pure date stored in B
    • If B and C store date-time values,
    =C-B returns the difference in decimal days.
    =DATEDIF(B,C,"D") returns the number of days between the two pure dates. It's identical to =DATE(YEAR(C),MONTH(C),DAY(C))-DATE(YEAR(B),MONTH(B),DAY(B))
    =DATEDIF(B,C,"M") returns the number of months between the two pure dates.
    =DATEDIF(B,C,"Y") returns the number of years between the two pure dates.
    Three other variants are available which use the parameters "MD","YM" and "YD".
    Yvan KOENIG (from FRANCE lundi 25 août 2008 15:23:34)

    KOENIG Yvan wrote in his "*STORED DATE-TIME VALUES - BASICS*" section:
    The minimal time unit is the second because time values are in fact a pseudo string representing the number of seconds between the date-time and the base date-time, 1 janvier 1904 00:00:00.
    This is not exactly true. Numbers files store date-time values in a string format consistent with ISO 8601:2004. This format explicitly includes year, month, day, hour, minute, & second values.
    This may be verified by examining the uncompressed index.xml file in a Numbers package. For example, the first day of 1904 is stored as cell-date="1904-01-01T00:00:00+0000" & of the year 0001 as cell-date="0001-01-01T00:00:00+0000." This format is not a numeric value of seconds from a base date-time, often referred to as a "serial time" format, that is used in applications like AppleWorks (or Excel?).
    Note that the time value (all that follows the "T" in the string) actually has four components, the last one (following the plus) representing the time zone offset from UTC time in minutes. AFAIK, Numbers does not set this to anything besides "+0000" but interestingly, it will attempt to interpret it if set by manually editing the file. For example, change cell-date="1904-01-01T00:00:00+0000" to cell-date="1904-01-01T00:00:00+0120" & the cell will display the last day of December of 1903 as the date, but will still show the time as 00:00:00. This suggests a future version of Numbers might be time zone aware, but currently it is unreliable & not fully implemented.
    Anyway, Numbers does not use the first day of 1904 as a reference for stored date-time values, although it will add that date to "dateless" time values imported from AppleWorks spreadsheets. Although I have not verified this, I believe it will also seamlessly translate between ISO & serial time formats as needed for Excel imports & exports, using the first day of 1900 as needed.
    Some other things to note about the ISO standard:
    • It permits fractional time values in the smallest time unit present, so for example "T10:15:30" could be represented as "T10:15.5" but Numbers does not support this -- the cell will appear empty if the index file is manually edited this way.
    • It does not stipulate whether date-time values represent intervals or durations (although it includes an explicit format for intervals between any two date-time values, known as a period). This means a future version of Numbers could support durations without the addition of a new data storage type, but legacy & import/export issues could make this too impractical to implement.
    • It supports a variety of other formats, including date-only, time-only, day-of-year, week-of-year, & various truncations (just hours & minutes, for example). All are unambiguous so a future version of Numbers could support them, but files generated with those versions would not be backwards compatible with the current version.
    For completeness, I will add that instead of using complex formulas to manipulate single-cell date-time values in Numbers, it is sometimes more straightforward to use multiple cells, one for each unit of time (for example, days, hours, minutes, & seconds), plus simple arithmetic formulas to combine them. Since each unit is a simple number, this results in highly portable, accurate, & "future-proof" tables, especially for durations. This is particularly useful for multimedia work in which the units might include video or film frames or audio samples.

  • Questions on StringTokenizer, trim(), and parsing.

    im doing an assignment that requires parsing and havent had that much practice with parsing regular text from a file, ive been doing mostly parsing from a html. my question is if im parsing a line and i need 2 different types of information from it, should i just tokenize it twice or do it all at once, assuming the text format is always the same. for example
    String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";if parsed correctly with StringTokenizer it would be 4 Strings(this is a test) and 10 ints for the countdown of numbers. now since the Strings doesnt have a delimiter such as a comma i can use the default delimiter which is the whitespace but then would that mean i would have to parse that same String twice since the numbers has "," has a delimiter? also should i worry about the whitespace that is separating the numbers after the comma? i did a small driver to test out the trim() using this and both outputs were the same. this may be a dumb question but if i call the trim() it eliminates the white space right, therefore i can just set "," as my delimiter, question is why is my output for both Strings the same?
        String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";
        String trimmed = test.trim();
        System.out.println(input);
        System.out.println("\n" + trimmed);SORRY if its confusing im trying not to reveal too much of the hw assignment and just get hints on parsing this efficiently. Thanks in advance

    similar example on how to parse out the numbers with
    "," as a delimiter. thanks in advanceThe following is a simple recursive descent parser to parse a comma delimited list of numbers "(1, 2, 3, 5, 6)". The grammar parser by this code is
    START -> LPAREN LIST RPAREN
    LIST -> NUMBER TAIL
    TAIL -> COMMA LIST | LambdaThe nonterminals NUMBER, LPAREN, RPAREN, and COMMA are defined by the regular expressions in the code.
    Lexical analysis is done by the function advanceToken(). It stores the next token in the variable "lookahead" for further processing. The parse tree is represented recursively through the functions start(), lparen(), rparen(), list(), number(), tail(), comma(), which match the corresponding symbols in the grammar. Finally, translation is done in the function number(). All it does is put the numbers it finds into the List intList. you can modify it to your needs.
    This code originally parsed simple arithmetic expressions, but it took only ten minutes to parse lists of integers. It's not perfect and there are several obvious improvement that will speed up performance, however the strength of the design is that it can be easily changed to suit a variety of simple parsing needs.
    import java.util.regex.*;
    import java.util.*;
    public class RDPParenList {
        private static final Pattern numberPat=
                        Pattern.compile("([1-9]\\d*)|0");
        public static final Object NUMBER = new Object();
        public static final Pattern commaPat = Pattern.compile(",");
        public static final Object COMMA = new Object();
        public static final Pattern lparenPat=
                        Pattern.compile("\\(");
        public static final Object LPAREN = new Object();
        public static final Pattern rparenPat=
                        Pattern.compile("\\)");
        public static final Object RPAREN = new Object();
        public static final Token NULLTOKEN = new Token(null, null);
        String input;
        String workingString=null;
        Token lookahead=NULLTOKEN;
        List intList = new ArrayList();
        /** Creates a new instance of RecursiveDescentParse */
        public RDPParenList(String input) {
            this.input=input;
        public void parse(){
            workingString=input;
            advanceToken();
            start();
            if(! "".equals(workingString))
                error("Characters still remaining in input '" + workingString + "'");
        private void advanceToken() {
            // calling advanceToken must give a token
            if("".equals(workingString))
                error("End of input reached unexpectedly");
            // prune the old token, and whitespace...
            if(lookahead != NULLTOKEN){
                int cutPoint = lookahead.symbol.length();
                while(cutPoint < workingString.length() &&
                        Character.isWhitespace(workingString.charAt(cutPoint))){
                    ++ cutPoint;
                workingString=workingString.substring(cutPoint);
            // Now check for the next token, starting with the null token...
            if("".equals(workingString)){
                lookahead=NULLTOKEN;
                return;
            Matcher m=numberPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), NUMBER);
                return;
            m=commaPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), COMMA);
                return;
            m=lparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), LPAREN);
                return;
            m=rparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), RPAREN);
                return;
            error("Error during lexical analysis. Working string: '" +
                           workingString + "'");
        private void start() {
            lParen(); list(); rParen();
        private void lParen(){
            if(lookahead.attrib == LPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected '('");
        private void rParen(){
            if(lookahead.attrib == RPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ')'");
        private void list() {
            number(); tail();
        private void number() {
            if(lookahead.attrib == NUMBER){
                // Do something with the number!
                try{
                    intList.add(new Integer(lookahead.symbol));
                catch(NumberFormatException e){
                    // This shouldn't happen if the lexer is working...
                    e.printStackTrace();
                    error("Unknown Error");
                advanceToken();
            else error("Error at token '" + lookahead.symbol + "' expected a number");
        private void tail() {
            if(lookahead.attrib == COMMA){
                comma(); list();
            else {
                // Lambda production
        private void comma() {
            if(lookahead.attrib == COMMA){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ','");
        private void error(String message){
            System.out.println(message);
            System.exit(-1);
        public static class Token{
            public Token(String symbol, Object attrib) {
                this.symbol=symbol;
                this.attrib=attrib;
            public String symbol;
            public Object attrib;
        public static void main(String []args){
            if(args.length == 0)
                return;
            System.out.println("\nParse String: " + args[0]);
            RDPParenList p=new RDPParenList(args[0]);
            p.parse();
            System.out.println("OK!");

Maybe you are looking for

  • Print 6 Slides per Page

    Is it possible to have Keynote print 6 slides per page the way PowerPoint for Windows does (3 slides in each of two columns on the page), rather than 6 slides vertically along the left side of the page?

  • Displaying an image in a form

    hi, i am trying to display an image in a form. The code worked fine in j2me emulator, but when i converted the program to a jar and ran the same program in my mobile phone. i get an exception in Image.createImage(.. method and exception value is just

  • LG Spectrum autorotate has stopped and phone will not recalibrate, how do I fix it?

    All of a sudden the autorotate does not work, and the phone gives me a "cannot calibrate" message when I try to recalibrate it. Anyone know how to fix this?

  • How i know the password of user created by su10

    Hi all, i have created three users by SU10 and gave the role y_functional_all , but the problem is that how i will get the password for that user to connect. rgds imran

  • Confused about how to install Lightroom 5

    Hi There, I have all my serials in 1Password and generally keep very good software records but while I have serials for Lightroom versions 1-4, I can't see anything for v5. Is it possible that Lightroom 5 was an in-app upgrade or special upgrade that