big negative number - postive giving postivie only - asp.net

I have temp2 value -52340.0 and hslColor.Luminosity is 240.0
When Dim temp1 As Double = (hslColor.Luminosity - temp2). It shoud give -ve number but I am getting always positive number.
results should nbe -52100, but I am getting +52100. How to handle this?

240 - (-52340) = 52580
Do you remember what happens if you subtract a negative?

This is what you are doing:
Dim temp1 as Double = (240 - -52340.0)
You are subtracting a negative.

results should nbe -52100, but I am getting +52100.
That's a lie. You should be getting 52580, not 52100.
If you substitute the values in like this:
240 - -52340
You're subtracting a negative, so it's the same as adding a positive:
240 + 52340
Which equals 52580.
How to handle this?
To get the intended result of -52100, either use this if temp2 is always negative:
Dim temp1 As Double = (hslColor.Luminosity + temp2)
or use this, if you need to subtract the absolute value of temp2, whether it can be negative or positive:
Dim temp1 As Double = (hslColor.Luminosity - Math.Abs(temp2))

Dim temp1 As Double = (240 - -52340)
the answer will be 52580
Dim temp1 As Double = (240 - 52340)
the answer will be -52100

Related

Large Integer division error in Julia when using UInt128 data type

I get incorrect results when I divide large integers of type UInt128. The error seems to occur about the same spot, significant figure wise, that a float64 will round its result. Using something simple, like dividing by 2, I can easily verify that I am not getting the correct answer. Also I can use BigInt types to verify that I am indeed seeing what seem to be significant figure errors while using UInt128 variable.
I am still fairly new to Julia and not familiar enough with the inner workings of the language to know why this is happening and when to expect these kinds of results. Can someone please give me some insight as to why/how this is occurring.
For example:
xb::BigInt = big"40282366920938463463374607431768211456"
ub::BigInt = big"2"
xu::UInt128 = parse(UInt128,"40282366920938463463374607431768211456")
uu::UInt128 = parse(UInt128, "2")
println("Initial value for xb = " , xb)
println("Initial value for xu = " , xu)
gb::BigInt = xb / ub
gu::UInt128 = xu / uu
g1::UInt128 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
g2 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
println("Division result using BigInt = ", gb)
println("Division result using UInt128 variables = ", gu)
println("Division result using UInt128 typecasts = ", g1)
println("Division result using UInt128 julia decides = ", g2)
println(typeof(g2))
Output:
julia> include("uint128_test.jl")
Initial value for xb = 40282366920938463463374607431768211456
Initial value for xu = 40282366920938463463374607431768211456
Division result using BigInt = 20141183460469231731687303715884105728
Division result using UInt128 variables = 20141183460469232747289327097010454528
Division result using UInt128 typecasts = 20141183460469232747289327097010454528
Division result using UInt128 julia decides = 2.0141183460469233e37
Float64
Integer division in Julia promotes to Float64. you want to use div or รท for integer division.
For a very brief version of this, 3/2 = 1.5

Simple recursive series in matlab

I'm trying to get the sum of the first 120 terms of a series:
a(n) = (10+a(n-1))(1.005)^n
I've tried two approaches, but I don't know which mistakes I'm making.
Approach #1:
nval = 1
mval = zeros(120,1)
for nval=1:120
if nval <= 120 %counting up from 1 to 120
if nval == 1 %modifying first term to avoid 0 index
mval(1) = (10)*(1.005)
nval = nval +1;
else
mval(nval) = (10+mval(nval-1))*(1.005)^nval; %Assigning
nval = nval +1;
end
end
end
which results in a column vector with 10.05 at the top and zeroes for the rest. If if omit the opening definition of mval as zeroes, I get the same result as
Approach #2:
a(1)=10.05; %defining first term to avoid 0 index
for n=2:120, a(n)= (10+a(n-1))*(1.005)^n; end
which results in something far too large.
(The correct value for a(120) is ~1646.99)
Edit: my mistake and apologies - my series was wrong; the (1.005)^n is NOT to the nth power, but merely 1.005. Using this, both methods work.
Thanks to one and all for answers and suggestions

Decimal Calculations in ASP/VBScript

This is more of a math/logic question so I apologize if this isn't the proper place to ask this question, I've just been working at this for hours and can't seem to find the right solution. I have a have a field in a database that I'm using to store baseball innings pitched that stores decimal numbers with one decimal place. The decimal places can only end in .0, .1 or .2. For those not familiar with baseball statistics, innings pitched is usually stored as something like 50.1, which means a pitcher pitched 50 full innings and 1/3 of another inning. 50.2 would be 50 full innings and 2/3 of another inning.
So for example, these numbers could be stored in the database:
10.1
26.2
13.2
7.1
28.5 could not be stored in the database, because it ends in .5, and it can only end in .0, .1 or .2.
My issue, is that on my webpage, I am trying to add these numbers to get a total number of innings pitched, but the total isn't correct.
In my example above, technically that adds up to 56.6, when it should add up to 58.0.
Another example would be if I was adding the numbers 28.1, 61.2 and 69.1. That adds up to 158.4 when I need it to add to 159.1.
On example I found online was to take:
(3 * totalInnings)/3
but that still doesn't give me what I'm looking for in some cases. Any guidance would be appreciated.
This could probably be improved, but seems to work ok:
There are two functions.
ToThirds converts an innings amount (eg. 10.1) to a more useful number of thirds (there are 31 thirds in 10.1).
ToInnings converts an amount in thirds back to an innings amount.
The first lines (Response.Write...) are your examples which return the same result as you calculated.
<%
Response.Write "<p>" & ToInnings(ToThirds(10.1) + ToThirds(26.2) + ToThirds(13.2) + ToThirds(7.1))
Response.Write "<p>" & ToInnings(ToThirds(28.1) + ToThirds(61.2) + ToThirds(69.1))
Function ToThirds(varInnings)
Dim varNumber, varRemainder
varNumber = Int(varInnings)
varRemainder = varInnings - varNumber
varNumber = (varNumber * 3) + (varRemainder * 10)
ToThirds = varNumber
End Function
Function ToInnings(varNumber)
Dim varInnings, varRemainder
varInnings = varNumber / 3
varRemainder = varInnings - Int(varInnings)
varInnings = Int(varInnings)
If varRemainder = 0 Or varRemainder >=7 Then
varInnings = varInnings & ".0"
ElseIf varRemainder < 4 Then
varInnings = varInnings & ".1"
ElseIf varRemainder < 7 Then
varInnings = varInnings & ".2"
End If
ToInnings = varInnings
End Function
%>
See innings as separate objects, not as decimal numbers with a different kind of adding. Creating objects is somewhat more work at first, but lay off their advantages when you use the object more often:
Option Explicit
' Constructor function that accept a score as string
Public function new_inning(score)
dim fullScore, partScore
fullScore = split(score, ".")(0)
If instr(score, ".") > 0 then
partScore = split(score, ".")(1)
else
partScore = 0
End if
Set new_inning = (new Inning).Init(fullScore, partScore)
End function
class Inning
private fullScore_, partScore_
Public Property Get FullScore()
FullScore = fullScore_
End Property
Public Property Get PartScore()
PartScore = partScore_
End Property
' Todo: insert some checking of valid scores
Public function Init(fScore, pScore)
fullScore_ = cInt(fScore)
partScore_ = cInt(pScore)
Set init = me
End Function
' Please note, this returns a new inning object so it keeps this object
' away from manipulation
Public Function Add(addInning)
Dim fScore, pScore
fScore = FullScore + addInning.FullScore
pScore = PartScore + addInning.PartScore
if pScore > 2 then
pScore = pScore - 3
fScore = fScore + 1
end if
Set Add = (new Inning).Init(fScore, pScore)
end Function
Public Function ToString()
ToString = cStr(fullScore) & "." & cStr(partScore)
End Function
end class
Dim myInning1, myInning2, resultInning
Set myInning1 = new_Inning("10.1")
Set myInning2 = new_Inning("15.1")
' Adding two innings
Set resultInning = myInning1.Add(myInning2)
Wscript.Echo resultInning.ToString() ' -> 25.2
' Inlining the adding of two innings
wscript.Echo resultInning.Add(new_inning("12.1")).ToString() ' -> 38.0
wscript.Echo resultInning.Add(new_inning("20.2")).ToString() ' -> 46.1

Vector Length in MapInfo

Does anyone know how to calculate the exact length of a vector in MapInfo?
Thanks.
I believe you can use
Dim vector_length As Float
vector_length = ObjectLen(Obj, "m")
I would prefere to use CartesianObjectLen instead of ObjectLen
CartesianObjectLen vs ObjectLen
dim o as object
select * from TABLE where Unique Column = Unique Code into sel
o=sel.obj
print(CartesianObjectLen(o, "m"))

Help modifying recursive function

Given a canvas, let's say 10x10, and given 3 rectangles/squares.
Canvas = 10x10
Rectangle 1 = 2x2
Rectangle 2 = 3x3
Rectangle 3 = 2x4
I've created a recursive function that loops every position of every rectangle on the canvas, and it works fine. (I've included the function below incase anyone wants to see it but I don't think it's necessary).
We can see that rectangle 1 and 2 are non rotatable, IE, if you rotate either of them 90 degrees essentially they are the same shape. However rectangle 3 is rotatable.
How do I change/construct the loop/recurisve function so that it loops every position of every rectangle, along with every possible rotation?
The aim is to loop through every possible fitting of the shapes on the canvas.
Thanks for any help!
Sub recurse(ByVal startPoint As Integer)
Dim x As Integer
Dim y As Integer
Dim validSolution As Boolean = isSolutionValid()
Dim loopXTo As Integer
Dim loopYTo As Integer
Dim solutionRating As Integer
'If parent nodes create invalid solution, we can skip (375 iterations from 1,600 iterations saving)
If validSolution = True Then
If (startPoint = 0) Then
loopXTo = Math.Floor((canvasCols - squareObjects(startPoint).sqRows()) / 2) '576 iterations from 1,680 iterations
loopYTo = Math.Floor((canvasRows - squareObjects(startPoint).sqCols) / 2) '31,104 iterations from 90,720 iterations
Else
loopXTo = canvasCols - squareObjects(startPoint).sqRows
loopYTo = canvasRows - squareObjects(startPoint).sqCols
End If
'Loop all positions on canvas
For x = 0 To loopXTo
For y = 0 To loopYTo
'Set coords of square
squareObjects(startPoint).setSquareCords(x, y)
'Phyiscally place it in canvas
placeSquareOnCanvas(x, y, squareObjects(startPoint).sqRows, squareObjects(startPoint).sqCols)
'Recursive, get next square
If (startPoint + 1 < totalSquares) Then
recurse(startPoint + 1)
Else
validSolution = isSolutionValid()
'Is solution valud
If (validSolution = True) Then
solutions = solutions + 1
End If
iterations = iterations + 1
'Response.Write("<br /><b>Iteration " & iterations & "</b>")
If (validSolution) Then
'Rate solution, record if best
solutionRating = rateSolution()
If solutionRating > bestCellSaving Then
bestCellSaving = solutionRating
copySolution()
End If
'Response.Write(" <span style='color:green'> <B>VALID SOLUTION</B></span> (" & rateSolution() & ")")
End If
'printCanvas(canvas)
End If
squareObjects(startPoint).removeSquare(canvas)
Next
Next
End If
End Sub
If you extract the loops in a separate routine the solution emerges relatively easily.
I have changed the validSolution logic a bit to make the code shorter - now we don't call recurse if the solution is invalid and we don't need to check for isSolutionValid() at the beginning of recurse(). These changes make counting the iterations harder so I removed that code, but it should be possible to add it later.
The recurse() routine without the last "If" statement should behave exactly as your code. The last "If" statement essentially performs the loops for a rotated rectangle.
I am not sure how removeSquare() is implemented, but it may need to know the orientation to be able to work correctly.
Sub recurse(ByVal startPoint As Integer)
Dim loopXTo As Integer
Dim loopYTo As Integer
If (startPoint = 0) Then
loopXTo = Math.Floor((canvasCols - squareObjects(startPoint).sqRows) / 2)
loopYTo = Math.Floor((canvasRows - squareObjects(startPoint).sqCols) / 2)
Else
loopXTo = canvasCols - squareObjects(startPoint).sqRows
loopYTo = canvasRows - squareObjects(startPoint).sqCols
End If
fitSqare(loopXTo, loopYTo, False)
If (squareObjects(startPoint).sqCols <> squareObjects(startPoint).sqRows) Then
fitSqare(loopYTo, loopXTo, True)
End If
End Sub
Sub fitSquare(ByVal loopXTo As Integer, ByVal loopYTo As Integer, ByVal rotate As Boolean)
Dim x As Integer
Dim y As Integer
Dim solutionRating As Integer
Dim validSolution As Boolean
'Loop all positions on canvas
For x = 0 To loopXTo
For y = 0 To loopYTo
'Set coords of square
squareObjects(startPoint).setSquareCords(x, y)
'Phyiscally place it in canvas
If (rotate) Then
placeSquareOnCanvas(x, y, squareObjects(startPoint).sqCols, squareObjects(startPoint).sqRows)
Else
placeSquareOnCanvas(x, y, squareObjects(startPoint).sqRows, squareObjects(startPoint).sqCols)
End If
validSolution = isSolutionValid()
'Is solution valud
If (validSolution) Then
'Recursive, get next square
If (startPoint + 1 < totalSquares) Then
recurse(startPoint + 1)
Else
solutions = solutions + 1
'Rate solution, record if best
solutionRating = rateSolution()
If solutionRating > bestCellSaving Then
bestCellSaving = solutionRating
copySolution()
End If
End If
End If
squareObjects(startPoint).removeSquare(canvas) 'removeSquare may require additional work to handle rotated state
Next
Next
End Sub
If the canvas is always a square then you don't need to change much. The result for the rotated rectangle 3 is the same as for the unrotated, except the origin of the Canvas is different. Imagine leaving the Rectangle 3 unrotated and rotating the canvas 90 degrees in the other direction. This means that you should be able to use some maths on the same results to get your answer.
Put your (x,y) coordinate loop in its own function. Then call the (x,y) coordinate loop on a rectangle of WxH, and then call it again on the rotated rectangle HxW.
Alternatively you can put the branching on the two rotations of your rectangle inside the (x,y) loop, after both coordinates have been picked, but before you make the recursive call.
In both cases you will need to be careful about whether your rotation causes the rectangle to exceed the height or width of your bounding box.
Can't you simply scan the list of shapes and for those that are rectangles (SizeX != SizeY) add a cloned rectangle with { SizeX = source.SizeY, SizeY = source.SizeX } (eg.: rotated rectangle)?
That would of course mean to do the loops twice (one for the unrotated list of shapes and one for the rotated one).
=> doing something like
squareObjects(startPoint) = squareObjects(startPoint).Rotate();
recurse(startPoint);
Frankly I don't think your implementation is the best- but if you don't want to make big changes and make separate routines you can just put the code for the rectangles twice in the same function-iteration.
So after:
'Phyiscally place it in canvas
placeSquareOnCanvas(x, y, squareObjects(startPoint).sqRows, squareObjects(startPoint).sqCols)
[......]
End If
squareObjects(startPoint).removeSquare(canvas)
You can do a check
IF the square is rectangle (width <> height)
then copy the same code again (in Then code) changing sqRows with sqCols in placeSquareOnCanvas().
The recursion will not be anymore linear, as this will make 2 recursive branches for each rectangle. Maybe it is not very nice written copying the same code 2 times, but the result will be right, the code changing is minimal and this straight solution based on your code will have more performance than trying other tweaks.

Resources