Friday, February 11, 2011

How to fix precision of variable

In c#

double tmp = 3.0 * 0.05;

tmp = 0.15000000000000002

This has to do with money. The value is really $0.15, but the system wants to round it up to $0.16. 0.151 should probably be rounded up to 0.16, but not 0.15000000000000002

What are some ways I can get the correct numbers (ie 0.15, or 0.16 if the decimal is high enough).

  • Use a fixed-point variable type, or a base ten floating point type like Decimal. Floating point numbers are always somewhat inaccurate, and binary floating point representations add another layer of inaccuracy when they convert to/from base two.

    Jon Skeet : Decimal is a floating point type too. It's just a floating *decimal* point.
    AaronSieb : Good to know. Edited to hopefully be a bit more accurate.
    sixlettervariables : Minor nitpick is that they're not 'inaccurate' rather they have a given precision. Just it is more natural for us to think in terms of decimal precision as opposed to binary precision :D
    Jon Skeet : sixlettervariables - I was going to make the same point, but felt I'd been nitpicking too much recently. Basically float/double have a set of exactly representable values - it's just not always the set that developers expect it to be.
    AaronSieb : Perhaps I should have stated that arbitrary math operations are always a little inaccurate (due to the aliasing to/from representable values, and our tendency to use numbers easily representable in base ten rather than binary)? It's close enough to let it ride, though :)
    From AaronSieb
  • 'decimal' type was designed especially for this

    From rslite
  • In Patterns of Enterprise Application Architecture, Martin Fowler recommends using a Money abstraction

    http://martinfowler.com/eaaCatalog/money.html

    Mostly he does it for dealing with Currency, but also precision.

    You can see a little of it in this Google Book search result:

    http://books.google.com/books?id=FyWZt5DdvFkC&pg=PT520&lpg=PT520&dq=money+martin+fowler&source=web&ots=eEys-C_vdA&sig=jckdxgMLSRJtGDYZtcbYST1ak8M&hl=en&sa=X&oi=book_result&resnum=6&ct=result

    Berryl : One thing I like about Fowler's Money pattern is it makes the actual storage type an implementation detail. Cheers
    From Lou Franco
  • Money should be stored as decimal, which is a floating decimal point type. The same goes for other data which really is discrete rather than continuous, and which is logically decimal in nature.

    Humans have a bias to decimal for obvious reasons, so "artificial" quantities such as money tend to be more appropriate in decimal form. "Natural" quantities (mass, height) are on a more continuous scale, which means that float/double (which are floating binary point types) are often (but not always) more appropriate.

    From Jon Skeet
  • A decimal data type would work well and is probably your choice.

    However, in the past I've been able to do this in an optimized way using fixed point integers. It's ideal for high performance computations where decimal bogs down and you can't have the small precision errors of float.

    Start with, say an Int32, and split in half. First half is whole number portion, second half is fractional portion. You get 16-bits of signed integer plus 16 bits of fractional precision. e.g. 1.5 as an 16:16 fixed point would be represented as 0x00018000. Or, alter the distribution of bits to suit your needs.

    Fixed point numbers can generally be added/sub/mul/div like any other integer, with a little bit of work around mul/div to avoid overflows.

    From spoulson
  • What you faced is a rounding problem, which I had mentioned earlier in another post

    Can I use “System.Currency” in .NET?

    And refer to this as well Rounding

    From faulty

How to build a solution to target 64 bit environment?

Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated.

cheers,

RWendi

  • This page on 2003's lack of 64-bit targeting seems to address your issue: http://www.toymaker.info/Games/html/64_bit.html.

    The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development.

    In order to create 64 bit applications you need to install the latest Platform SDK from Microsoft (Microsoft Platform SDK for Windows Server 2003). The SDK, as well as having libraries for 32 bit programming, has 64 bit versions for AMD64 and IA64 (Intel) development.

    Getting the correct library and header file paths set up in Visual Studio proved surprisingly difficult. I wanted the choice of developing 32 bit or 64 bit projects. While the platform SDK comes with command files to set up the correct paths they wipe out any other paths. Since T2 uses DirectX I also needed the DirectX paths setting correctly.

    Upgrading to a newer edition of Visual Studio looks like the safer, non-hackish solution, if possible.

    RWendi : This seems to work partially. Yes, its using the 64 bit compiler, but somehow the 64 bit compiler in the platform sdk has some missing external dependencies. Going to try the windows sdk and see if it works.
    From warren
  • As Warren points out, this isn't easy with VS2003. You need to install the x64 compiler from the platform SDK.

    We ran this way for a couple of years (starting with even earlier versions and the IA64 compiler). There were separate project configurations for X64 builds, so in addition to the normal DEBUG and RELEASE configurations we had DEBUG_X64 and RELEASE_X64.

    But you have to launch VS studio with the paths set up for either the x86 or x64 compilers & libraries. You couldn't switch between them on the fly. I believe there was a command line switch /useenv that told VS to set its various paths from environment variables. We had bat files to set this all up.

    It is messy, and every now and then we'd build the wrong project configuration for the environment which always took a while to sort out. You are much better off upgrading to VS2005/VS2008 where the target architecture is exposed directly in the GUI.

    From Rob Walker
  • Sounds like a viable solution... going to try it before accepting the answer. votes up!

    RWendi

    From RWendi

PHP5: Specifying a datatype in method parameters

I have a function that looks like this

class NSNode {
    function insertAfter(NSNode $node) {
        ...
    }
}

I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after nothing. The way I think about that is that null means "nothing", so I'd write my function call like this:

$myNode->insertAfter(null);

Except PHP throws an error saying that it was expecting an NSNode object. I'd like to stick to using the strict data typing in my function, but would like to be able to specify a null-esque value.

So, short of changing it to function insertAfter($node) { }, is there a way I can pass something else to that function?


Update: I've accepted Owen's answer because it answered the question itself. Everyone else's suggestions were really good and I'll actually be implementing them in this project, thanks!

  • No, you can't pass something else to the function as that defeats the purpose of the static typing. In this situation, something like C# nullable would be nice i.e. NSNode?

    I'd suggest creating NSNode::insertFirst() although I think that you have it the wrong way round, why is a node inserting itself, shouldn't the collection be inserting and taking the node as a parameter?

    From Geoff
  • sure, just set a default "null"

    function(NSNode $node = null) {
    // stuff....
    }
    

    result being:

    $obj->insertAfter(); // no error
    $obj->insertAfter(new NSNode); // no error
    $obj->insertAfter($somevar); // error expected NSNode
    
    From Owen
  • Better to have a function insertAtBeginning() or insertFirst() for legibility anyway.

    "The way you think of it" may not be the way the next guy thinks of it.

    insertAfter(null) might mean many things.

    Maybe null is a valid value and insertAfter means place it after the index that contains the value null.

How to implement a web page that scales when the browser window is resized?

How to implement a web page that scales when the browser window is resized?

I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized

i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way?

  • thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread

  • using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution

EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling

  • instead of using in css say "width: 200px", use stuff like "width: 50%"

    This makes it use 50% of whatever it's in, so in the case of:

    <body>
     <div style="width:50%">
      <!--some stuff-->
     </div>
    </body>
    

    The div will now always take up half the window horizontaly.

    Steven A. Lowe : this basically works for the initial layout, but you have to adjust the percentages to account for borders in different browsers, and also use ajax triggered by window resizing to resize the contents of the divs
  • Unless you have some specific requirement here I'm not sure why JS is needed here. Tabular layouts are the easy (and archaic) way to make fluid layouts in html, but div layouts with css allow for fluid layouts as well, see http://www.glish.com/css/2.asp

    Steven A. Lowe : javascript is required to refresh the contents when the browser window resizes
  • Yep sound like you want to look at a fluid CSS layout. For resources on this, just google fluid CSS layout, should give you a whole lot of things to check. Also have a look at this previous question for some good pointers.

  • Something else to consider is that JavaScript won't update continuously while the window is being resized, so there will be a noticeable delay/choppiness. With a fluid CSS layout, screen elements will update almost instantly for a seamless transition.

    Steven A. Lowe : javascript is required to trigger content refresh, the page is not all static
    Zach : which is fine, I was referring to using JavaScript with the onresize event.
    From Zach
  • The best way that I have seen to do this is to use the YUI CSS Tools and then use percentages for everything. YUI Grids allow for various fixed width or fluid layouts with column sizes specified as fractions of the available space. There is a YUI Grids Builder to help lay things out. YUI Fonts gives you good font size controls. There are some nice cheat sheets available that show you how to lay things out and useful things like what percentage to specify for a font size of so many pixels.

    This gets you scaling of the positioning but scaling of the entire site, including font sizes, when the browser window resizes is a bit trickier. I'm thinking that you are going to have to write some sort of browser plugin for this which means that your solution will be non portable. If you are on an intranet this isn't too bad as you can control the browser on each client but if you are wanting a site that is available on the internet then you may need to rethink your UI.

    Steven A. Lowe : thanks for the links, very interesting tools!
  • It really depends on the web page you are implementing. As a general rule you're going to want 100% CSS. When sizing elements that will contain text remember to gravitate towards text oriented sizes such as em, ex, and not px.

    Floats are dangerous if you're new to CSS. I'm not new and they are still somewhat baffling to me. Avoid them where possible. Normally, you just need to modify the display property of the div or element you're working on anyway.

    If you do all of this and scour the web where you have additional difficulties you'll not only have pages that resize when the browser does so, but also pages that can be zoomed in and out by resizing text. Basically, do it right and the design is unbreakable. I've seen it done on complex layouts but it is a lot of work, as much effort as programming the web page in certain instances.

    I'm not sure who you're doing this site for (fun, profit, both) but I'd recommend you think long and hard about how you balance out the CSS purity with a few hacks here and there to help increase your efficiency. Does your web site have a business need to be 100% accessible? No? Then screw it. Do what you need to do to make your money first, then go hog wild with your passion and do anything extra you have time for.

    Steven A. Lowe : the site's already done - it was for a client - but looking back at it i don't like what i had to do to get it work
  • After trying a solution by the book I got stuck with incompatibility's in either Firefox or IE. So I did some tinkering and came up with this CSS. As you can see, the margins are half of the desired size and negative.

    <head><title>Centered</title>
    <style type="text/css">
    body { 
            background-position: center center;
            border: thin solid #000000;
            height: 300px;
            width: 600px;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -150px;
            margin-right: auto;
            margin-bottom: auto;
            margin-left: -300px;
        }
    </style></head>
    

    Hope that helps

    Steven A. Lowe : interesting solution, but i can't set the body to a fixed size
    From Florian
  • Use percentages! Say you have a "main pane" on which all your page's content lies. You want it to be centered in the window, always, and 80% of the width of the window.

    Simply do this:
    #centerpane{ margin: auto; width: 80%; }

    Tada!

    Steven A. Lowe : i want the page content to always fill the window, and resize itself when the window resizes
  • Thanks for all of the suggestions! It looks like the ugly stuff i had to do was necessary. The following works (on my machine, anyway) in IE and FireFox. I may make an article out of this for CodeProject.com later ;-)

    This javascript goes in the <head> section:

    <script type="text/javascript">
    var tmout = null;
    var mustReload = false;
    
    function Resizing()
    {
        if (tmout != null)
        {
            clearTimeout(tmout);
        }
        tmout = setTimeout(RefreshAll,300);
    }
    function Reload()
    {
        document.location.href = document.location.href;
    }
    //IE fires the window's onresize event when the client area 
    //expands or contracts, which causes an infinite loop.
    //the way around this is a hidden div set to 100% of 
    //height and width, with a guard around the resize event 
    //handler to see if the _window_ size really changed
    var windowHeight;
    var windowWidth;
    window.onresize = null;
    window.onresize = function()
    {
        var backdropDiv = document.getElementById("divBackdrop");
        if (windowHeight != backdropDiv.offsetHeight ||
            windowWidth != backdropDiv.offsetWidth)
        {
            //if screen is shrinking, must reload to get correct sizes
            if (windowHeight != backdropDiv.offsetHeight ||
                windowWidth != backdropDiv.offsetWidth)
            {
                mustReload = true;
            }
            else
            {
                mustReload = mustReload || false;
            }
            windowHeight = backdropDiv.offsetHeight;
            windowWidth = backdropDiv.offsetWidth;
            Resizing();
        }
    }
    </script>
    

    the <body> starts off like this:

    <body onload="RefreshAll();">
        <div id="divBackdrop" 
            style="width:100%; clear:both; height: 100%; margin: 0; 
                padding: 0; position:absolute; top:0px; left:0px; 
                visibility:hidden; z-index:0;">
        </div>
    

    the DIVs float left for the layout. I had to set the height and width to percentages just shy of the full amount (e.g., 99.99%, 59.99%, 39.99%) to keep the floats from wrapping, probably due to the borders on the DIVs.

    Finally, after the content section, another javascript block to manage the refreshing:

    var isWorking = false;
    var currentEntity = <%=currentEntityId %>;
    
    //try to detect a bad back-button usage;
    //if the current entity id does not match the querystring 
    //parameter entityid=###
    if (location.search != null && location.search.indexOf("&entityid=") > 0)
    {
        var urlId = location.search.substring(
            location.search.indexOf("&entityid=")+10);
        if (urlId.indexOf("&") > 0)
        {
            urlId = urlId.substring(0,urlId.indexOf("&"));
        }
        if (currentEntity != urlId)
        {
            mustReload = true;
        }
    }
    //a friendly please wait... hidden div
    var pleaseWaitDiv = document.getElementById("divPleaseWait");
    //an example content div being refreshed via AJAX PRO
    var contentDiv = document.getElementById("contentDiv");
    
    //synchronous refresh of content
    function RefreshAll()
    {
        if (isWorking) { return; }  //no infinite recursion please!
    
        isWorking = true;
        pleaseWaitDiv.style.visibility = "visible";
    
        if (mustReload)
        {
            Reload();
        }
        else
        {
            contentDiv.innerHTML = NAMESPACE.REFRESH_METHOD(
                (currentEntity, contentDiv.offsetWidth, 
                 contentDiv.offsetHeight).value;
        }
    
        pleaseWaitDiv.style.visibility = "hidden";
        isWorking = false;
        if (tmout != null)
        {
            clearTimeout(tmout);
        }
    }
    
    var tmout2 = null;
    var refreshInterval = 60000;
    
    //periodic synchronous refresh of all content
    function Refreshing()
    {
        RefreshAll();
        if (tmout2 != null)
        {
            clearTimeout(tmout2);
            tmout2 = setTimeout(Refreshing,refreshInterval);
        }
    }
    
    //start periodic refresh of content
    tmout2 = setTimeout(Refreshing,refreshInterval);
    
    //clean up
    window.onunload = function() 
    {
        isWorking = true;
        if (tmout != null)
        {
            clearTimeout(tmout);
            tmout = null;
        }
        if (tmout2 != null)
        {
            clearTimeout(tmout2);
            tmout2 = null;
        }
    

    ugly, but it works - which i guess it what really matters ;-)

  • use ems. jontangerine.com and simplebits.com are both amazing examples. Further reading - The Incredible Em & Elastic Layouts with CSS by Jon Tan

    Steven A. Lowe : thanks andy! I did end up using ems for fonts in this project after calculating font sizes in px on a previous project [which worked, but not well!]
    From Andy Ford
  • < body onresize="resizeWindow()" onload="resizeWindow()" > PAGE < /body >

        /**** Page Rescaling Function ****/
    
        function resizeWindow() 
        {
            var windowHeight = getWindowHeight();
            var windowWidth = getWindowWidth();
    
            document.getElementById("content").style.height = (windowHeight - 4) + "px";
        }
    
        function getWindowHeight() 
        {
            var windowHeight=0;
            if (typeof(window.innerHeight)=='number') 
            {
                windowHeight = window.innerHeight;
            }
            else {
                if (document.documentElement && document.documentElement.clientHeight) 
                {
                    windowHeight = document.documentElement.clientHeight;
                }
                else 
                {
                    if (document.body && document.body.clientHeight) 
                    {
                        windowHeight = document.body.clientHeight;
                    }
                }
            }
            return windowHeight;
        }
    

    The solution I'm currently working on needs a few changes as to width otherwise height works fine as of so far ^^

    -Ozaki

    From Thqr

how do you package up silverlight dlls into a xap file?

Just updated build server with rc0 and surprise no chiron. Wondering how you package up a xap file without chiron.

  • Hey Brian, you can get chiron from http://www.codeplex.com/sdlsdk -- it was decided to be removed from the SL SDK core tools, but is still a part of the DLR SDK which is available.

    Brian Leahy : i did see that in my research but other research showed it hadn't been updated for rc0, so it will output the version number of beta 2 in the manifest. We could use that and manually change the version numbers i guess...
    From Tim Heuer
  • More specifically you can still use MSBuild. The targets should be located at C:\program files\MSBuild\Microsoft\Silverlight\v2.0 if you need to look at them or modify...your .csproj(or.vbproj) can also have pre/post build tasks for MSBuild as well.

    From Tim Heuer

.NET // vs /// Comments convention

I am just checking out F#, so apologies if this is a silly question, but in the VS2008 F# CTP 1.9.6.2 'Tutorial' project, both // and /// are used for commenting code.

Is there a functional difference between the two slash vs three slash commenting, or is it convention (as it appears in the tutorial code) to comment a function with /// and use // for everything else?

  • /// is for documentation comments. VS will use it when generating intellisense information.

  • Using three slashes (///) is a C# convention for XML Documentation Comments that is adopted by F# as well.

  • It's similar to /* comment */ vs /** documented comment */ in Java.

    The latter works the same, but is also recognised by documentation software to be developer documentation - not just a note.

    Scott Dorman : Which only helps if you know what those comment constructions do in Java, which wasn't the question.
    From Dean

What might this gdb output mean?

Trying to create my first iPhone app that would play back audio. When I try to set up playback, messages like these appear in gdb:

=shlibs-removed,shlib-info=[num="54",name="AudioIPCPlugIn",kind="B",dyld-addr="0x2c2000",reason="dyld",requested-state="E",state="E",path="/System/Library/Extensions/AudioIPCDriver.kext/Contents/ Resources/AudioIPCPlugIn.bundle/Contents/MacOS/AudioIPCPlugIn", description="/System/Library/Extensions/AudioIPCDriver.kext/Contents/Resources/ AudioIPCPlugIn.bundle/Contents/MacOS/AudioIPCPlugIn",loaded_addr="0x2c2000",slide="0x2c2000",prefix=""]

=shlibs-removed,shlib-info=[num="55",name="AppleHDAHALPlugIn",kind="B",dyld-addr="0x2cb000",reason="dyld",requested-state="E",state="E",path="/System/Library/Extensions/AppleHDA.kext/Contents/PlugIns/ AppleHDAHALPlugIn.bundle/Contents/MacOS/AppleHDAHALPlugIn", description="/System/Library/Extensions/AppleHDA.kext/Contents/PlugIns/ AppleHDAHALPlugIn.bundle/Contents/MacOS/AppleHDAHALPlugIn",loaded_addr="0x2cb000", slide="0x2cb000",prefix=""]

Not being familiar with gdb, I'm interested to know in general what sort of problems these types of messages might refer to.

  • AFAIK, those are information message about unloaded dynamic libraries, i don't think it denotes any problem or error.

  • Those are informational messages from the system which let you know when a dynamic library gets unloaded from your executable. I presume that they occur in this case because you are perhaps doing a bit too much destructing (ie, unloading bundles, etc.) when you try to shut down your app's connection to CoreAudio.

    From Nik Reiman