Getting Time Remaining - math

Say something happens at a rate of 5000 per hour and there's some amount remaining (let's say 2500 for example's sake).
How would I get the hours, minutes, and seconds remaining?
I would think it'd be something along the lines of:
hour = floor(remaining / perHour)
mins = floor(remaining % perHour / 60)
secs = floor(remaining % perHour % 60)
However calculating that back up using the below returns the incorrect amount.
time = hour + (mins / 60) + (secs / 60 / 60)
time * perHour // 3472.2 - not 2500
The time should be shorter so I'm obviously calculating this wrong. I would appreciate it if someone were to explain where I went wrong.
EDIT: I'm aware this isn't the Maths SE but the Maths SE is supposed to be for high level maths, and this is the next best fit.
Figured out a method, but it may not be the best so I'll leave this question up for a while longer.
hour = floor(remaining / perHour)
mins = floor(remaining / perHour * 60) - hour * 60
secs = floor(remaining / perHour * 3600) - mins * 60 - hour * 3600

Our question is how much time remains, and we know the rate of the process. No sweat, we establish a rate ( Items/minute, Items/sec) and divide the number of remaining elements by the rate. We could use any unit of time we want as long as we keep it consistent -- personally, I like rates in per-second because Hz.
A Demo
function getRemainingTime(remainingItems) {
const processRatePerHour = 5000;
const processRate = (processRatePerHour / 60 / 60); // 1.3888 per second
remainingSeconds = remainingItems / processRate;
return {
hours: (remainingSeconds / 3600),
minutes: (remainingSeconds / 60),
seconds: remainingSeconds
};
}
function showProgress(remainingItems) {
var time = getRemainingTime(remainingItems);
var list = document.createElement('ul');
var processEnd = moment().add(time.seconds, 's');
list.innerHTML = `
<ul>
<h3> With ${remainingItems} remaining, we will be finished ${processEnd.fromNow()}. </h3>
<li> Hours Remaining: ${time.hours} </li>
<li> Minutes Remaining: ${time.minutes} </li>
<li> Seconds Remaining: ${time.seconds} </li>
</ul>`;
document.body.appendChild(list);
}
// Let's try it out!
showProgress(4999);
showProgress(2500);
showProgress(100);
body {
font-family: 'Helvetica', sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<h2> Please Accept My Answer v.0.2. </h2>

Related

Need help wit heartrate calculation for watch

So I'm trying to animate a fake heartbeat for my Android wear watchface. I have an API that grabs the heartrate in BPM and the current millisecond now I'm trying to use an equation to make an image "beat" to the BPM. Here's the psuedocode:
IF (Millis / HeartRate) % (1000 / HeartRate) <= 1)
Opacity = 100;
ELSE
Opacity = 75;
ENDIF
I'm really not sure if I calculated it properly. I don't think the image is properly flashing at the correct rate. Any help with the math would be appreciatred!
A value in BPM is a frequency, rather than a period of time:
b BPM = b / 60s = b/60 * s^-1
The period of the oscillation is
T = 1/f = 60s / b = 60/b s
If we have a time in milliseconds, then we can work out the modulo vs the period:
remainderInSeconds = CurrentTimeInSeconds % T
= (CurrentTimeInMilliseconds * 1e-3) % T
= (CurrentTimeInMilliseconds * 1e-3) % (60/BeatsPerMinute)
fraction = remainderInSeconds / Period
= [(CurrentTimeInMilliseconds * 1e-3) % T] / T
= (CurrentTimeInMilliseconds * 1e-3 / T) % 1
= (CurrentTimeInMilliseconds * 1e-3 / (60/BeatsPerMinute)) % 1
= (CurrentTimeInMilliseconds * 1e-3 * BeatsPerMinute / 60)) % 1
= (CurrentTimeInMilliseconds * BeatsPerMinute / 60e3)) % 1
Then you can check whether the fraction is below your threshold; if you want the pulse to last a 20th of the period, then check if fraction < 1/20.
Alternatively just calculate the remainder in seconds, if you want the pulse to last a specific amount of time rather than a portion of the period.
I managed to compile a new code using a different variable from the watch API. This other variable is essentially a number between 0 and 359 which steps up at mere decimals per frame. (The variable is normally used for a smooth motion second hand).
I also decided to use a sine wave and RGB shaders instead of opacity. Here is the new code
Green = 0
Blue = 0
Red = 100 * math.sin(HeartRate * SecondsRotationSmooth / 60)
Using this particular variable isn't ideal, but it at least gives me a better looking code. If anyone wants to give a better answer please do!

Maths help on function to return number of items in container

This should be simple enough but the maths for this eludes me. I am looking to express this in C++ but some psuedo code will happily do, or just the maths really.
The function will be given a number of a container and it will return the number of items in that container. The number of items is based on their number and halves at certain number height.
The first halving is at number 43,200 and then every time after it is the gap number of containers between the previous halving plus 43,200
It may sounds confusing, it will look like the following.
1 to 43200 = 512
43201 to 86400 = 256
86401 to 129600 = 128
129601 to 172800 = 64
172801 to 216000 = 32
216001 to 259200 = 16
and so
So if a number up to 43,200 is given the result is 512, the number 130,000 will return 64. The value can be less than 1 taking up several decimal places.
global halvingInterval = 43200
global startingInventory = 512
def boxInventory(boxNumber):
currentInventory = startingInventory
while(boxNumber > halvingInterval):
currentInventory = currentInventory/2
boxNumber -= halvingInterval
return currentInventory
This code will take the box number. It will keep subtracting the halving interval until you get to the right inventory area, and then return the inventory when it is done.
N = (noitems + 1) / 43200;
L2 = log(512) / log(2);
answer = exp( log(2) * (1 + L2 - N) );

Seconds to hours, minutes and seconds?

I am very bad at math, but what is the mathematical equation (in its simplest possible form) to convert 3605 seconds to hours, minutes and seconds?
3605 / 60 / 60 = 1,0013888888 hours
Am I on the right track?
time.hours = seconds / 3600;
time.minutes = (seconds - 3600 * time.hours) / 60;
time.seconds = seconds - 3600 * time.hours - 60 * time.minutes;
This doesn't work, but it should, shouldn't it?
Yes, you are on the right track. Here's a breakdown.
3605 secs
60 sec in a minute 3605/60 = 60.083 minutes
60 minutes in an hour 60.083 = 1.001 hour
24 hours in a day 1.001/24 = .0417 of a day
Let t be the total number of seconds
h = int(t / 3600)
m = int((t - 3600 * h) / 60)
s = t - 3600 * h - 60 * m
See code here: http://ideone.com/OzLF8g
1 minute = 60 seconds
1 hour = 60 minutes = 60*60 seconds
So,
if
x = 3605
a = number of hours
b = number of minutes
c = number of seconds
then
a = ⌊ x / (60*60) ⌋
b = ⌊ (x - (a*60*60)) / 60 ⌋
c = x - ((a*60*60) + (b*60))
⌊⌋ means quotient
hours = seconds // 3600
minutes = (seconds // 60) % 60
sec = seconds % 60
try it

Convert decimal representing time to hour, minutes, seconds

I have a decimal. The range of this decimal is between 0 and 23.999999. This decimal represents a time. For example, if the decimal is 0.25, then the time it represents is 12:15 AM. If the decimal is 23.50, the time it represents is 11:30 PM.
I have three variables:
- Hours
- Minutes
- Seconds
Using this decimal, how do I fill in the Hours, Minutes, and Seconds values?
Well, here's an answer in C#, but it's generally the same idea in most languages:
int hours = (int)hoursDecimal;
decimal minutesDecimal = ((hoursDecimal - hours) * 60);
int minutes = (int)minutesDecimal;
int seconds = (int)((minutesDecimal - minutes) * 60);
The hours should be pretty easy.
There are 60 minutes in 1 hour, so get the decimal part, multiply it by 60, and take the integer. Take the decimal again, multiply it again by 60, and you have your seconds.
For example, let's take the number 20.38490
We know it's hour 20, or 8 PM.
This leaves us with the number .38490
Multiplying with 60, we get 23.094 minutes.
Multiplying .094 with 60, we get 5 seconds.
you can use the floor function to strip off the hours and leave the minuites and seconds as a fraction of an hour. Then you can use the floor function again to strip off the minuites as a fraction of an hour. you are then left with the seconds ( as fractions of an hour )
below a simple example to print hours and mins sunrise is in fractional hours since midnight
printf( "sunrise %ld:%ld, \n",
(long)floor( sunrise ),
(long)(floor( sunrise * 60 ) - 60 * floor( sunrise )) );
Whatever language you use, you can do this using the math functions: MOD and FLOOR/TRUNC
Let "dec" be the decimal variable
trunc(mod(dec, 1)) => hours
trunc(mod(dec * 60, 60)) => minutes
trunc(mod(dec * 3600, 60)) => seconds
In C#, you can truncate a decimal to int using just explicit casting, e.g.
int seconds = (int) ((dec * 3600) % 60)

Convert unix timestamp to julian

How can I convert from a unix timestamp (say 1232559922) to a fractional julian date (2454853.03150).
I found a website ( http://aa.usno.navy.mil/data/docs/JulianDate.php ) that performs a similar calculation but I need to do it programatically.
Solutions can be in C/C++, python, perl, bash, etc...
The Unix epoch (zero-point) is January 1, 1970 GMT. That corresponds to the Julian day of 2440587.5
So, in pseudo-code:
function float getJulianFromUnix( int unixSecs )
{
return ( unixSecs / 86400.0 ) + 2440587.5;
}
I know that this is an old post, but I'll just say ...
The answer given by Jason Cohen is a good approximation of the conversion.
There is a problem though that relates to the number of seconds in one day. A day is not -exactly- 86400 seconds long, and periodically seconds are added to days in order to keep time synchronized with the various observable standards. These are called Leap Seconds (https://en.wikipedia.org/wiki/Leap_second). Leap seconds are added to UTC in order to keep it within 1 second of UT1.
It stands to reason that as more and more time has elapsed since Jan 1, 1970, the simple conversion above will accrue more and more error from "actual observable time." Between 1972 and 2013 there were added 25 leap seconds.
Part of the beauty and the simplicity of Julian Day numbers is that they don't represent date strings at all. They are just a count of elapsed time since the start of the Julian Epoch, much like POSIX time is a continuous count of milliseconds since the POSIX Epoch. The only problem that exists, then, is when you try to map a Julian Day number to a localized date string.
If you need a date string that is accurate to within a minute (in 2013), then you'll need an algorithm that can account for leap seconds.
Here is my JavaScript code to convert Unix timestamp to Julian. Originally is showing the current date and time, but with a little mod is answer to your question:
function computeJulianDate(DD,MM,YY,HR,MN,SC) {
with (Math) {
HR = HR + (MN / 60) + (SC/3600);
GGG = 1;
if (YY <= 1585) GGG = 0;
JD = -1 * floor(7 * (floor((MM + 9) / 12) + YY) / 4);
S = 1;
if ((MM - 9)<0) S=-1;
A = abs(MM - 9);
J1 = floor(YY + S * floor(A / 7));
J1 = -1 * floor((floor(J1 / 100) + 1) * 3 / 4);
JD = JD + floor(275 * MM / 9) + DD + (GGG * J1);
JD = JD + 1721027 + 2 * GGG + 367 * YY - 0.5;
JD = JD + (HR / 24);
}
return JD;
}
function getUTCDateTimeOrJD(now,jd=0) {
var hours = now.getUTCHours();
var minutes = now.getUTCMinutes();
var seconds = now.getUTCSeconds()
var month = now.getUTCMonth() + 1;
var day = now.getUTCDate();
var year = now.getUTCFullYear();
if (jd==1)
return computeJulianDate(month, day, year, hours, minutes, seconds);
else
return day+". "+month+". "+year+". "+hours+":"+minutes+":"+seconds;
}
var unixTime = 1473294606;
getUTCDateTimeOrJD(new Date(unixTime*1000));
getUTCDateTimeOrJD(new Date(unixTime*1000),1);
Working JSFiddle example here
This question was asked over 13 years ago as of writing. That's pretty wild. Thanks to eapo's JS formula I converted it to PineScript v5 and in testing its at least really close. I don't think perfect accuracy would even be relevant for most (if any) TradingView applications. So, I didn't go as far as to ensure perfect accuracy. But it works. Thanks eapo, you saved me a bunch of time.
EDIT: TradingView displays times in the stock/currency exchange time zone. So, it became necessary to create additional arguments to provide for the UTC offsets that exchanges utilize.
[IMPORTANT: Keep in mind that exchanges that utilize daylight savings time will shift from UTC - n to UTC - n - 1 depending on the DST state. You must update your UTC offset argument accordingly.]
// Julian Date & Partial Day in CST
computeJulianDate(dd, mm, yy, hr, mn, sc, offset=0, live=false) =>
HR = hr
HR := hr + (mn / 60) + (sc / 3600)
GGG = 1
if year <= 1585
GGG := 0
float JD = -1 * math.floor(7 * (math.floor((mm + 9) / 12) + yy) / 4)
S = 1
if ((mm - 9)<0)
S :=-1
A = math.abs(mm - 9)
J1 = math.floor(yy + S * math.floor(A / 7))
J1 := -1 * math.floor((math.floor(J1 / 100) + 1) * 3 / 4)
JD := JD + math.floor(275 * mm / 9) + dd + (GGG * J1)
JD := JD + 1721027 + 2 * GGG + 367 * yy
JD := JD + (HR / 24)
barsInSession = timeframe.isintraday ? ((24 * 60) / timeframe.multiplier) : timeframe.multiplier
barsInSession := math.floor(barsInSession) == barsInSession and timeframe.isintraday ? barsInSession - 1 : math.floor(barsInSession)
offsetInc = 1 / barsInSession
offsetCt = (offset * ((barsInSession / 24) * offsetInc))
JD := live ? JD + offsetCt : math.floor(JD - offsetCt) - 0.5
JD

Resources