Page 1 of 2 12 LastLast
Results 1 to 40 of 58

Thread: Creating User-Defined Types.

  1. #1

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Creating User-Defined Types.

    Well I had a thread going that branched out to this topic, so rather completely veering off the main topic there, I felt creating a new thread was adequate.

    So as the title says, I'm trying to create a user-defined type. It's not a simple type at that but a user here had showed me a way to fix all my problems. That was to create a type BigDecimal. Which my initial thought was to utilize the BigInteger type. Being that the Integer Part, and Fractional parts would be split off into two variables, both BigIntegers. Which would be combined at the end as a "decimal". However I have many many questions see that this is my first attempt at truly creating a type of my own. So as of right now I'm basically swinging in the dark here.


    My first concert was assigning the variable. For example if I had...

    vbnet Code:
    1. Dim BigDec As BigDecimal = 1000285.00001883

    I'm not at all sure of how to accomplish this. I feel it must be in a string format first, split by the decimal point, then split of both sides accordingly..

    But truly I'm pretty confused here. Any information or pointers to creating user-defined types of this stature would be extremely helpful.

    I also have googled up some information on User-Defined types, but nothing has been what I'm looking for. I did learn a lot however just everything I could find out there wasn't "advanced" but more or less the basic stuff that I could've done myself.
    Last edited by DavesChillaxin; Nov 19th, 2011 at 12:01 PM.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  2. #2
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Hi Daves,

    It's a good idea to start a new thread on this, but I think your thread title may be misleading. A "user-defined type" could be any Class, Structure, Interface, Enum etc. you define yourself. I know from the last thread that you want to make a BigDecimal type, and it's logical to make that a structure. After all BigIntegers are structures (and if I remember correctly so are Doubles, Decimals and a load of other types in the .Net framework).

    A Structure can look very much like a class. It can have Variables, Constants, Properties, a Sub New, other Subs and Functions and so on. The main difference is that a structure is a Value type, while a class is a Reference type.

    I'll give you a slightly more detailed quick sketch of my idea of a BigDecimal structure, but please note that I haven't tried it. It could be rubbish and I'm sure it will end up being at least 10 times as long. I certainly wouldn't waste any more time on it without Googling for bigdecimal (which I know will yield some relevant hits) and taking a good look at what other people have done.
    vb Code:
    1. Public Structure BigDecimal
    2.     Public MultipliedValue As BigInteger
    3.     Public Shared Property Multiplier As Integer
    4.  
    5.     Public Overrides Function ToString() As String
    6.         Dim str As String = MultipliedValue.ToString
    7.         Return str.Insert(MultipliedValue.Length - Multiplier, ".")
    8.     End Function
    9.  
    10.     Public Function Multiply(bd As BigDecimal) As BigDecimal
    11.         Dim output As BigDecimal
    12.         output.MultipliedValue = Me.MultipliedValue * bd.MultipliedValue / Multiplier
    13.         Return output
    14.     End Function
    15.  
    16.     Public Function Divide(divisor As BigDecimal) As BigDecimal
    17.          'and so on
    18.     End Function
    19.  
    20. End Structure

    BB

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: Creating User-Defined Types.

    Also look into overloading the +-*/ and \ operators so that you can use your type in normal equations. You might also want to be able to use them with other numeric types, so there could be a few overloads for you, but it will make for a much more versatile type.
    My usual boring signature: Nothing

  4. #4

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Well this is what I've had so far, since yesterday when I originally posted this. Don't mind some of it though, I'm still experimenting.


    vbnet Code:
    1. Public Structure BigDecimal
    2.  
    3.             Dim IntegerPart As BigInteger
    4.             Dim FractionalPart As BigInteger
    5.  
    6.  
    7.             Sub New(ByVal value As BigDecimal)
    8.                 Me.IntegerPart = value.IntegerPart
    9.                 Me.FractionalPart = value.FractionalPart
    10.             End Sub
    11.  
    12.             Public Shared Operator =(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As Boolean
    13.                 If value1.Equals(value2) Then
    14.                     Return True
    15.                 End If
    16.                 Return False
    17.             End Operator
    18.  
    19.             Public Shared Operator <>(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As Boolean
    20.                 Return Not value1=value2
    21.             End Operator
    22.        
    23.             Public Shared Operator -(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As BigInteger
    24.  
    25.             End Operator
    26.        
    27.             Public Shared Operator +(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As BigDecimal
    28.                 Dim result As New BigDecimal
    29.                 Dim fracTmp1 As String = value1.FractionalPart.ToString()
    30.                 Dim fracTmp2 As String = value2.FractionalPart.ToString()
    31.  
    32.                 With result
    33.                     .IntegerPart = value1.IntegerPart+value2.IntegerPart
    34.                    
    35.                     'Both must be of the same length
    36.                     If fracTmp1.Length > fracTmp2.Length Then
    37.                         fracTmp2.PadRight(fracTmp1.Length, "0"c)
    38.                     ElseIf fracTmp1.Length < fracTmp2.Length Then
    39.                         fracTmp1.PadRight(fracTmp1.Length, "0"c)
    40.                     End If
    41.                     .FractionalPart = 0
    42.                 End With
    43.  
    44.                 Return result
    45.             End Operator
    46.        
    47.             Public Shared Operator /(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As BigInteger
    48.  
    49.             End Operator
    50.        
    51.             Public Shared Operator *(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As BigInteger
    52.  
    53.             End Operator
    54.        
    55.             Public Shared Operator ^(ByVal value1 As BigDecimal, ByVal value2 As BigDecimal) As BigInteger
    56.  
    57.             End Operator
    58.  
    59.             Public Overloads Function ToString() As String
    60.                 Return IntegerPart.ToString & "." & FractionalPart.ToString()
    61.             End Function
    62.  
    63.         End Structure


    In the + Overload I found it being difficult to add the fractional parts, for the fact that things can get tricky when handling the decimal point. For example

    1.8969 + 1.8888.. For me I have to add the two integer parts, which is 2. Then the fractional parts which is actually 1.7857. There I realized I need to bump my integer part by one, or what have you depending on what the fractional parts add up too. Unless there is an easier way of doing this that I'm unaware of.. I was just going to literally add the fractional parts as you would on a piece of paper. Start at the end and work my way up, in which case if anything must be added to the integer part, it would be left over. However I see this method taking some time if the fractional part is long enough.. except it's simple addition so I'm not aware of the impact it would have, so I'm going to experiment a little bit today and see whats my best option.
    Last edited by DavesChillaxin; Nov 20th, 2011 at 12:48 PM.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  5. #5
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Creating User-Defined Types.

    Quote Originally Posted by Shaggy Hiker View Post
    Also look into overloading the +-*/ and \ operators so that you can use your type in normal equations. You might also want to be able to use them with other numeric types, so there could be a few overloads for you, but it will make for a much more versatile type.
    Also, less than, less than or equal, and the greater than counterparts might be useful. Maybe even and, or, xor. I did mention in the other thread that the decimal point location would need to be accounted for.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  6. #6

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by dbasnett View Post
    Also, less than, less than or equal, and the greater than counterparts might be useful. Maybe even and, or, xor. I did mention in the other thread that the decimal point location would need to be accounted for.

    Oh geez, I forgot about >, >=, <, <=. And, Or, and Xor will come lastly once I'm able to make some headway here. I'm still a little stuck on keeping track of the decimal points location - If I used a single BigInteger. Cause of that I'm using two for now. Which will make things a little easier on my part.. I hope.

    I haven't had much time at all today to get anything done, so I'm hoping by tonight I'll have some more for you folks to gander at
    Last edited by DavesChillaxin; Nov 20th, 2011 at 04:33 PM.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  7. #7

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Before I can get started I need a little help...

    How do I do this?

    vbnet Code:
    1. Dim b As BigDecimal
    2.  
    3. b = BigDecimal.TryParse(TextBox1.text)
    4. 'or
    5. b = 1000.0001

    I'm having trouble understanding how to first assign the values..

    Do I simply have to overload the = operand? One returning a boolean, the other returns BigDecimal..

    I'm sure I could figure out the TryParse easily, but the other I'm completely baffled on. I'm just not sure if I'll always have to input the values strictly as a String or BigDecimal seeing that there is no other equivalent data type that could be "equal" to a BigDecimal.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  8. #8

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    shoot.. I just realized a problem. I cannot convert 00001 into a BigInteger value.. I may need my fractional part in a string format I'm considering a single BigInteger then simply keeping track of the decimal.. somehow.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  9. #9
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Quote Originally Posted by DavesChillaxin View Post
    shoot.. I just realized a problem. I cannot convert 00001 into a BigInteger value.. I may need my fractional part in a string format I'm considering a single BigInteger then simply keeping track of the decimal.. somehow.
    Maybe you could add an integer field to the Structure to record the number of leading zeros in the fractional part. BB

  10. #10

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by boops boops View Post
    Maybe you could add an integer field to the Structure to record the number of leading zeros in the fractional part. BB
    I actually just thought of this, and I'm attempting it right now. My + operand works, just the leading zeros throw everything off.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  11. #11

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    My attempt was successful, though I didn't realize how often I'd have to keep track of the leading zeros. First I had to keep track of them when parsing a string value to my BigDecimal. Secondly I had to add them back in before the calculations, then thirdly when returning the result of the calculations(because again I had to parse the values back to BigIntegers)

    I'm sure I could finalize a bit, but so far it works .. just the addition. Attached is screen shot of it at working.


    EDIT: I've just realized that at some point this bigdecimal of mine must have a limit of some sort. If I design it to have the capacity of a BigInteger which is infinite, and I do things right then a simple 1/3 could easily trip a never ending process.. eventually maxing the memory limits.
    Attached Images Attached Images  
    Last edited by DavesChillaxin; Nov 20th, 2011 at 08:43 PM.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  12. #12
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Keep it up, Daves, this is looking really good.
    Edit: msdn says for BigInteger that the practical limit is when you get an OutOfMemory exception. You don't want to do that, because it means a crash. You might be able to forestall a crash by using a MemoryFailPoint, which results in an InsufficientMemoryException that you can catch. I've posted about that before so if you're interested, you could possibly search this forum for MemoryFailPoint. Still, it could be a lot of work since you would need it in practically every calculation. As an interim, I see from msdn that the BigInteger.ToString default output is limited to 50 places of decimals. Maybe you could take that as an example, and use 50 places for the Integer part and 50 places for the Fractional part.

    BB

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: Creating User-Defined Types.

    I wouldn't bother with And, Or, and XOR. That works well for integers, but becomes really strange when you try to do that with decimals.

    It's interesting that you found addition and subtraction of decimals to be difficult. Not surprising, though. Addition and subtraction of Integers is VASTLY easier than multiplication and division, but the reverse is true for floating point values, as you are finding.
    My usual boring signature: Nothing

  14. #14
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: Creating User-Defined Types.

    Now you should calculate PI and hold it in your BigDecimal

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  15. #15

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    @boops boops First, thanks I'm starting to think so myself, and if successful could be useful and helpful to a lot of coders a like.

    Secondly...
    Quote Originally Posted by boops boops View Post
    As an interim, I see from msdn that the BigInteger.ToString default output is limited to 50 places of decimals.
    I saw this to while I continuously research along side every step I make. Which is when I got the idea that I could have some out of memory issues when dealing with repeating decimals and irrational numbers such as 1/3 and Pi. The 50 limit seems like a good idea and could avoid any errors I have when converting to strings, but I actually would like to go a little further than that for a limit. I was thinking maybe 500 to 1000 for starters. Simply because thats nothing compared to what our memory can store to date while still giving me extremely larger decimals than ever allowed before.

    I'd also like to add that this ToString nonsense of limits and returning useless information (to me), is beginning to be a huge nuisance. I feel in my opinion, ToString should return values exactly as-is, and not in an unspecified format by default. It should have to be by choice to have returned values in a different format, just like they've always been.



    Quote Originally Posted by Shaggy Hiker View Post
    It's interesting that you found addition and subtraction of decimals to be difficult. Not surprising, though. Addition and subtraction of Integers is VASTLY easier than multiplication and division, but the reverse is true for floating point values, as you are finding.
    It's only difficult because this is rather a different thinking to me than what I'm used to. I mean I'm not even sure if my methods are practical, though they work. I'm just a little skeptical that there are better methods out there of accomplishing these similar tasks.

    The way I'm "adding" values is.. the integer part simply gets added normally (BigInteger+BigInteger). However I knew the fractional part could not be done this way, just because it almost must be done "backwards". So to do this I convert both values to strings, then in a for loop I start from the end of each variable and working my way backwards to the beginning. Each step of the way extracting a single number from both variables and adding them together, making sure I keep track of any remainders as such. Once the for loop as completed I convert the result string through BigInteger.TryParse() and assign the returning value to the FractionalPart of the returning BigDecimal. Seems a bit much for simple addition. So I can only imagine what I must do for anything more like you stated, such as multiplication and division. Regardless it works for me and seems to be quite quick at that, even for the larger numbers I've tried during tests.

    If you have any suggestions of another possible way I could be doing this please feel free to share. It's always much easier to find mistakes when reading others work - as I always say.



    Quote Originally Posted by stepdragon View Post
    Now you should calculate PI and hold it in your BigDecimal
    This is my goal But not quite yet.. I've got a lot to finish first before I'm able to do that. Simply because my BigDecimal will replace all Decimal variable types in my AdvancedMath class.. I need all the same functionality as the Decimal type, and all I have so far is the addition.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  16. #16
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: Creating User-Defined Types.

    Why can't you just do Two BigInts seperated by a decimal point, and when you need to add, you can add the Whole numbers by themselves, then after the decimal point, just multiply them by the decimal place, do addition, then divide them again. Does that make sense? basically use scientific notation. Then leading zeros make no difference, and you don't have to worry about it.

    (as part of this, can't you put an internal property or variable which will keep track of the number of decimal places?) it can simply update itself, that way you can modify leading zeros whenever, and still be able to simplify addition and subtraction.

    I hope I'm making sense.

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  17. #17

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by stepdragon View Post
    Why can't you just do Two BigInts seperated by a decimal point, and when you need to add, you can add the Whole numbers by themselves, then after the decimal point, just multiply them by the decimal place, do addition, then divide them again. Does that make sense? basically use scientific notation. Then leading zeros make no difference, and you don't have to worry about it.
    It kind of does lol. I mean I'm new to this whole concept. But I'm already using two BigInt values, the integer and fractional part. Both get handled on there own for calculations. The integer part was simple, just the fractional part had proven more difficult. Keeping track of the decimal point was proving to be a lot more work that what I had ended up doing.

    Scientific notations is also a new topic to me, though I understand it but only through looking at it, I cannot say I understand it in any more in depth than that.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  18. #18
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    I like Stepdragon's idea of using scientific notation. Instead of a BigDecimal, you could make a "BigDouble" type. It would have BigInteger for the mantissa, making the precision limitless, and an integer (or even BigInteger) power for the exponent. Tthe exponent could represent a power of 10. Maybe it would prove easier to code than BigDecimal, but I suppose you can't be sure until you try it.
    B
    B

  19. #19

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Isn't there loss of precision when using scientific notation? I slightly remember reading about it when doing a little research on them. Still though I'm a little confused how I'd do all this .. My first guess it would simply be the process of floating-points, but If I read correctly I could keep track of the precision lost - or the wobble as they so put it.

    Another question, does the nine's complement of subtraction method work with decimals? I've search high and low for an example but cannot find a single lead anywhere out there. All examples use either whole numbers or even binary, no decimals.


    EDIT: Wait, I just had to define mantissa before I could understand you fully. I see now where you guys are coming at, perhaps I need to read a little more up on scientific notation and see how to use them algebraically. For example, I have no clue how to add or subtract.. etc two SN values together. Unless first they must be converted to there standard decimal form, calculated, then back to scientific notation.. All in all, it makes sense cause he'd be right, I wouldn't have to keep track of any leading zeros.
    Last edited by DavesChillaxin; Nov 21st, 2011 at 09:46 AM.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  20. #20
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    I think you've understood. The imprecision is in the number of digits in the mantissa: 17 in the case of Double, pseudo-infinity in the case of BigDouble . BB

    Quote Originally Posted by DavesChillaxin View Post
    Isn't there loss of precision when using scientific notation? I slightly remember reading about it when doing a little research on them. Still though I'm a little confused how I'd do all this .. My first guess it would simply be the process of floating-points, but If I read correctly I could keep track of the precision lost - or the wobble as they so put it.

    Another question, does the nine's complement of subtraction method work with decimals? I've search high and low for an example but cannot find a single lead anywhere out there. All examples use either whole numbers or even binary, no decimals.


    EDIT: Wait, I just had to define mantissa before I could understand you fully. I see now where you guys are coming at, perhaps I need to read a little more up on scientific notation and see how to use them algebraically. For example, I have no clue how to add or subtract.. etc two SN values together. Unless first they must be converted to there standard decimal form, calculated, then back to scientific notation.. All in all, it makes sense cause he'd be right, I wouldn't have to keep track of any leading zeros.

  21. #21

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by boops boops View Post
    I think you've understood. The imprecision is in the number of digits in the mantissa: 17 in the case of Double, pseudo-infinity in the case of BigDouble . BB
    So now that we've figure a BigDouble may be more practical. How would I go about handling scientific notations in calculations? StepDragon kind of lost me when he explained? I think? It seems my knowledge of scientific notations isn't as clear as I'd like them to be especially for creating a type that would handle such data.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  22. #22
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Quote Originally Posted by DavesChillaxin View Post
    So now that we've figure a BigDouble may be more practical. How would I go about handling scientific notations in calculations? StepDragon kind of lost me when he explained? I think? It seems my knowledge of scientific notations isn't as clear as I'd like them to be especially for creating a type that would handle such data.
    See Wikipedia on scientific notation. It gives a concise rundown of the basic operations (multiply, divide, add & subtract). So they shouldn't be all that hard to code. I expect ToString and perhaps even power/^ will be reasonably straightforward. Maybe you need a shared Precision property, so you can set a general maximum precision for a particular program or class -- for example with 500 or 1000 as default. That would come into play in the arithmetic methods.

    Just thinking about the name. "Double" was so called because it was twice as precise as single, so it seems a bit stupid for something that can be infinitely precise. Maybe "BigFloat" would be a better name. Or is that some kind of ice-cream sundae? Discuss.

    BB

  23. #23
    Fanatic Member BlindSniper's Avatar
    Join Date
    Jan 2011
    Location
    South Africa
    Posts
    865

    Re: Creating User-Defined Types.

    Well, I have created a fraction class and I was on my way to create a BigDecimal class, I then read this thread, I then read the format specification on normal floating point numbers, now I want to create massive float, and after that I want to make a float with infinite precision. reading through how a IEEE 754(standard floating point) works really shed some light on this subject for me.

    And as for the name: In reality it is a Big Decimal number so BigDecimal seems appropriate, although I like the sound of BigDouble more.

    Useful CodeBank Entries of mine
    Expand Function
    Code Compiler
    Sudoku Solver
    HotKeyHandler Class

    Read this to get Effective help on VBForums
    Hitchhiker's Guide to Getting Help at VBF

  24. #24
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Creating User-Defined Types.

    Just me thinking out loud...

    Code:
    Imports System.Numerics
    Public Class Form1
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim s As String = New String("0"c, 99)
            Dim foo1 As numString = New numString("-001." & New String("0"c, 99) & "1")
            Dim foo2 As numString = New numString("1234." & New String("0"c, 98) & "12")
    
            'testing the addition of the decimal parts only
            Dim b1 As BigInteger = foo1.DecimalPart
            Dim b2 As BigInteger = foo2.DecimalPart
            Dim b3 As BigInteger = b1 + b2
            Debug.WriteLine(b3.ToString)
            Dim b5 As BigInteger = foo1.IntegerPart 'make sure minus works
            Debug.WriteLine(b5.ToString)
        End Sub
    End Class
    
    Class numString
    
        Private Shared decPT As String = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
        Private Shared grpSep As String = System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator
        Private Shared minusSign As String = System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign
    
        Public Sub New(realNumberAsString As String)
            Me.NumParts(realNumberAsString)
        End Sub
    
        Private Sub NumParts(realNumberAsString As String)
            Dim foo As Integer
            Dim idx As Integer
            Me._integer.Length = 0
            Me._decimal.Length = 0
    
            For idx = 0 To realNumberAsString.Length - 1
                Dim s As String = realNumberAsString.Substring(idx, 1)
                Select Case s
                    Case " "
                    Case minusSign
                        Me._minus = True
                    Case decPT
                        idx += 1
                        Exit For
                    Case grpSep 'ignore
                    Case Else
                        If Integer.TryParse(s, foo) Then
                            Me._integer.Append(s)
                        Else
                            'error!!!
                        End If
                End Select
            Next
            For idx = idx To realNumberAsString.Length - 1
                Dim s As String = realNumberAsString.Substring(idx, 1)
                If Integer.TryParse(s, foo) Then
                    Me._decimal.Append(s)
                Else
                    'error!!!
                End If
            Next
    
            If Me._integer.Length = 0 Then
                Me._integer.Append("0")
            ElseIf Me._minus Then
                Me._integer.Insert(0, minusSign)
            End If
    
            If Me._decimal.Length = 0 Then Me._decimal.Append("0")
        End Sub
    
        Private _integer As New System.Text.StringBuilder
        Private _decimal As New System.Text.StringBuilder
        Private _minus As Boolean = False
        Private Shared max As Integer = 100 '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    
        ReadOnly Property IntegerPart As BigInteger
            Get
                Dim rv As BigInteger = BigInteger.Parse(Me._integer.ToString)
                Return rv
            End Get
        End Property
    
        ReadOnly Property DecimalPart As BigInteger
            Get
                Dim rv As BigInteger = BigInteger.Parse(Me._decimal.ToString.PadRight(max, "0"c))
                Return rv
            End Get
        End Property
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  25. #25
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: Creating User-Defined Types.

    OK HOLD UP!!!!!

    I think everyone misunderstood me when I mentioned Scientific Notation... I did *NOT* mean use scientific notation, I was using S.N. as an example to show what I was going for... so let me explain better.


    What if you did your type like this:

    Lets say we want to hold the number:

    1025316452333000.00023000560004

    Now, If we already have BigInteger which can hold virtually limitless digits in it lets look at the number like this:

    (This is one number, I'm using colors so we don't lose our place)
    102531645233300000023000560004

    Now we can hold this entire number in a single BigInt. Next, we need to know where the decimal place is. We create a hidden variable within the structure, which will track where the decimal place is (just like the power in scientific notation)

    so we would have:

    1025316452333000.............. < - 14 places after the decimal.

    Therefore 14 places for the decimal.

    Now we can store this inside the BigDecimal Structure like this:

    BigInt = 102531645233300000023000560004
    Dec_P = 14 (hidden to the user, held in an integer within the structure) (I'm assuming this is possible)

    Then just output and modify calls accordingly. Does that clarify my suggestion at all?


    For the addition, you would simply line up the decimals (by adding leading, or trailing zeros) remove all the decimals, Add the numbers together, and then put back the decimal, and remove any leading or trailing zeros.

    Simple, Right?

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  26. #26
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    @Stepdragon. I think that is much the same as what we have been talking about in the past few posts. It is pretty similar to the Decimal type, only bigger. "Scientific representation" isn't limited to the format used in the Double type, with a fractional mantissa and a power of 10.

    I'm not sure if it's so important to keep the exponent part (the power of 10 or the number of decimal places, however you like to describe it) hidden. There might turn out to be situations where you want to get or set the mantissa and exponent directly.

    BB

  27. #27
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Creating User-Defined Types.

    @step - I think I like it It shouldn't be real hard to get the decimal points to line up...(famous last words).

    From an algorithmic perspective this is interesting, but I can't imagine reading a number like:

    4247243572034500204752.0000000000000000000000000000000000000000000000000000000000000000314159265
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  28. #28
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: Creating User-Defined Types.

    Quote Originally Posted by dbasnett View Post
    @step - I think I like it It shouldn't be real hard to get the decimal points to line up...(famous last words).

    From an algorithmic perspective this is interesting, but I can't imagine reading a number like:

    4247243572034500204752.0000000000000000000000000000000000000000000000000000000000000000314159265
    Why not? its just:
    Bigint: 42472435720345002047520000000000000000000000000000000000000000000000000000000000000000314159265
    Dec: 73

    Oh and aligning decimals is the easy part, just look at the numbers:

    Code:
       1.005   < - 3
            +
    1.000005   < - 6
    Add Zeros to the end of the number that has fewer digits:

    Code:
    1.005000   < - 6
            +
    1.000005   < - 6
    Remove decimals and add

    1005000 + 1000005 = 1005005

    Add Decimal Back:

    1.005005

    Remove any trailing zeros if needed (shouldn't need to do this with addition, other operators may need it) and adjust the decimal count accordingly
    Last edited by stepdragon; Nov 21st, 2011 at 07:20 PM.

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  29. #29
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Quote Originally Posted by stepdragon View Post
    Why not? its just:
    Bigint: 42472435720345002047520000000000000000000000000000000000000000000000000000000000000000314159265
    Dec: 73
    The way I see it, the purpose of the BigDecimal (now my preferred name again) is to allow calculations with accurate intermediate values. Having an output with a huge number of decimal places would be wanted only rarely -- say for testing purposes, to impress your boss, or to satisfy Pi mystics. The default ToString representation could be similar to Double but with a larger exponent range. For example:

    4247243572034500204752 * 10^500577832

    Of course there should be an option to output more decimal places in the mantissa when required.

    BB

  30. #30
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    Re: Creating User-Defined Types.

    Quote Originally Posted by boops boops View Post
    The way I see it, the purpose of the BigDecimal (now my preferred name again) is to allow calculations with accurate intermediate values. Having an output with a huge number of decimal places would be wanted only rarely -- say for testing purposes, to impress your boss, or to satisfy Pi mystics. The default ToString representation could be similar to Double but with a larger exponent range. For example:

    4247243572034500204752 * 10^500577832

    Of course there should be an option to output more decimal places in the mantissa when required.

    BB
    I would imagine it as holding all of the data, before after, and including the decimal place. And then you could implement different output formats. For example ToString(Format) and having different options, such as Sci-Not. Decimal, or whatever else.


    I would also do something like a

    .ToDecimal
    .ToInteger

    and so on, then within the code, check if the currently held number CAN be put into those numbers, if so return it in that format, otherwise return -1 or something. That way you could convert between types when needed.

    Same thing with New(Byval Input as Float) and so-on

    If you're wrong, you'll learn. If I'm wrong, I'll learn. Try something new and go from there. That's how we improve.

    CodeBank: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio - Star Rating Control
    Useful Links: HOW TO USE CODE TAGS

  31. #31
    Member
    Join Date
    May 2010
    Posts
    60

    Re: Creating User-Defined Types.

    Quote Originally Posted by DavesChillaxin View Post
    Before I can get started I need a little help...

    How do I do this?

    vbnet Code:
    1. Dim b As BigDecimal
    2.  
    3. b = BigDecimal.TryParse(TextBox1.text)
    4. 'or
    5. b = 1000.0001

    I'm having trouble understanding how to first assign the values..

    Do I simply have to overload the = operand? One returning a boolean, the other returns BigDecimal..

    I'm sure I could figure out the TryParse easily, but the other I'm completely baffled on. I'm just not sure if I'll always have to input the values strictly as a String or BigDecimal seeing that there is no other equivalent data type that could be "equal" to a BigDecimal.
    Inside the class
    ---------------------
    Public Shared Widening Operator CType(ByVal value As Single) As Bigdecimal
    return new bigdecimal(value)
    End Operator

    Public Shared Narrowing Operator Ctype(ByVal value as String) As Bigdecimal
    Return new bigdecimal(value)
    End Operator

    public sub new(ByVal Value as single)
    Do your conversion here
    End sub

    Public sub new(ByVal Value as String)
    Do your conversion here
    End sub
    --------------------------------------------

    Narrowing if there is a loss
    Widening if there is no loss

    Widening single to bigdecimal because it can hold all the posible single values
    Narrowing string to bigdecimal because a big decimal cannot hold letters

    Be sure to write al the ctypes you will need from and to other types

    If you do it well the compiled will do al the steps for you:
    b = 1000.0001 to b= bigdecimal.Ctype(1000.0001) to b = new bigdecimal(1000.0001)

    it works for structures too

    Steps to do by visual studio:
    variable as Type = [write the value directly here]
    guess the Type of [Write the value directly here] between the premade types ONLY
    call to shared Ctype of class/type/structure of the declared variable if [Write the value directly here] is of another type.
    assign the variable in a succesful conversion(if needed) or whine if there is no conversion function.
    Last edited by yo mismo; Nov 21st, 2011 at 09:19 PM.

  32. #32

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Holy cow! you guys gave me tons, I mean tons to think about! I knew this wasn't going to be a straight forward project, but one that would take a lot of brain storming and plenty of trial and errors. However I've had tons of homework tonight-seeing that I'm towards the end of my semester, and not to mention I've taken some benadryl. On benadryl my thinking is significantly impaired so I may need to review all of this tomorrow at work

    Though I may take stepdragons idea, and my initial thought of using just a single BigInteger, and a variable to hold the decimal places location. This would make all calculations a heck of a lot easier.

    I appreciate all of your help guy!
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  33. #33
    Fanatic Member BlindSniper's Avatar
    Join Date
    Jan 2011
    Location
    South Africa
    Posts
    865

    Re: Creating User-Defined Types.

    Why do you actually need limitless precision ? why not create a floating point datatype that can hold about 50 digits and 50 decimal places, you will never practically require more than 40 digits of precision for anything.

    Useful CodeBank Entries of mine
    Expand Function
    Code Compiler
    Sudoku Solver
    HotKeyHandler Class

    Read this to get Effective help on VBForums
    Hitchhiker's Guide to Getting Help at VBF

  34. #34
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Quote Originally Posted by BlindSniper View Post
    Why do you actually need limitless precision ? why not create a floating point datatype that can hold about 50 digits and 50 decimal places, you will never practically require more than 40 digits of precision for anything.
    Are you sure you aren't thinking about fixed point? Even Double allows for over 300 decimal places either side of the decimal point, although its precision is limited to 16 significant digits.

    The aim of BigDecimal would be to get away from the limitations of trying to pack the the number into 64 bits. Goodbye efficiency, hello precision. And why impose the limitation of a hard coded precision limit when it could be an Integer user setting (with that value as default)? It don't think it would make much difference to the code for the methods and operators. So I would suggest the following main fields:

    Code:
    Public Mantissa As BigInteger 'the integral data value
    Public Exponent As Integer 'the position of the decimal point
    Public Shared Property MaxPrecision As Integer = 100 'default value
    BB

  35. #35

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by boops boops View Post
    And why impose the limitation of a hard coded precision limit when it could be an Integer user setting (with that value as default)?

    Yup this is exactly what I was concidering. I though it over last night and realized this would ultimately fix my OutOfMemory error that could and most likely would occur if I had no cap. I wasn't actually thinking of calling it a "limit" though I like precision a lot more.

    Also I may stick with a BigDouble, and use a single BigInteger, simply because it would make all the calculations a lot easier. Than again I could do both BigDouble and BigDecimal(I've done quite some code work to function as such, and I'm not willing to throw it all out now). Both having their own specific use and functionality just as types do now.

    After I finish my 2 quizzes tonight I'll have something to show you guys. Unfortunately priorities comes first
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  36. #36
    Fanatic Member BlindSniper's Avatar
    Join Date
    Jan 2011
    Location
    South Africa
    Posts
    865

    Re: Creating User-Defined Types.

    @BB
    I just randomly thought of a number and it happened to be 50, but what I mean is for what use could you possibly need limitless precision ? A floating point is 4 bytes and a double is 8, create a 128 byte datatype, and you would have more precision than needed for all practical purposes, and you could possibly not sacrifice too much efficiency.
    I guess it all comes down to the speed difference between limited precision and unlimited precision. and which one is easiest to implement.

    Useful CodeBank Entries of mine
    Expand Function
    Code Compiler
    Sudoku Solver
    HotKeyHandler Class

    Read this to get Effective help on VBForums
    Hitchhiker's Guide to Getting Help at VBF

  37. #37
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Creating User-Defined Types.

    Quote Originally Posted by BlindSniper View Post
    @BB
    I just randomly thought of a number and it happened to be 50, but what I mean is for what use could you possibly need limitless precision ? A floating point is 4 bytes and a double is 8, create a 128 byte datatype, and you would have more precision than needed for all practical purposes, and you could possibly not sacrifice too much efficiency.
    I guess it all comes down to the speed difference between limited precision and unlimited precision. and which one is easiest to implement.
    Daves wants this type for evaluating mathematical expressions (it was clear in his previous thread if not this one). Decimal or even Double might be accurate enough for representing the end results. The trouble is that you can't be sure when the intermediate results could cause overflow. For example, suppose you wanted to evaluate this series (just to make something up):

    1 - 2^2/2! + 3^3/3! - 4^4/4! ... n^n/n!

    where the exclamation mark represents the factorial 1 * 2 * 3 * 4 ... *n. I happen to know that factorial 28 is too big to represent as decimal, so without a BigInteger or something else big, the evaluation will crash by term 28.

    If you want to make an expression evaluator that will evaluate anything the user throws at it, it might be hard to predict in advance just how much precision you need to avoid overflow. OK, evaluation may well take longer than the lifespan of the universe by term 42, but that's something we Magratheans have to deal with.

    PS. my mathematical knowledge is getting seriously overstrained here. How about asking on the Math forum?

    BB

  38. #38

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by BlindSniper View Post
    what use could you possibly need limitless precision?

    I honestly know deep down that anything limitless is impossible. For numbers that never end(which we know exist) clearly mean they never end. Memory cannot be limitless, plain and simple. But my goal for this is essentially just because I can. If my function which simplifies algebraic expressions can produce Pi/e with as many as 100,000 digits would be an achievement that I can be proud of.


    This all began with my own requiring of a type capable of holding the value of 1/16^20, and then some. Ultimately It would loop to around 1/16^100 for the precision of Pi I seek.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  39. #39
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Creating User-Defined Types.

    It is daves thread, but moving it to the math forum might prove enlightening. There are some incredibly bright people there.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  40. #40

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: Creating User-Defined Types.

    Quote Originally Posted by boops boops View Post
    PS. my mathematical knowledge is getting seriously overstrained here. How about asking on the Math forum?
    Oh I'll be sure to hit up that forum once I complete this BigDouble/BigDecimal. I will definitely need help with some mathematical aspects once my calculator is capable of handling most anything a user can throw at it.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width